Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/stdlib | repos/zig_workbench/BaseLVGL/lib/lvgl/src/stdlib/clib/lv_mem_core_clib.c | /**
* @file lv_malloc_core.c
*/
/*********************
* INCLUDES
*********************/
#include "../lv_mem.h"
#if LV_USE_STDLIB_MALLOC == LV_STDLIB_CLIB
#include "../../stdlib/lv_mem.h"
#include <stdlib.h>
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_mem_init(void)
{
return; /*Nothing to init*/
}
void lv_mem_deinit(void)
{
return; /*Nothing to deinit*/
}
lv_mem_pool_t lv_mem_add_pool(void * mem, size_t bytes)
{
/*Not supported*/
LV_UNUSED(mem);
LV_UNUSED(bytes);
return NULL;
}
void lv_mem_remove_pool(lv_mem_pool_t pool)
{
/*Not supported*/
LV_UNUSED(pool);
return;
}
void * lv_malloc_core(size_t size)
{
return malloc(size);
}
void * lv_realloc_core(void * p, size_t new_size)
{
return realloc(p, new_size);
}
void lv_free_core(void * p)
{
free(p);
}
void lv_mem_monitor_core(lv_mem_monitor_t * mon_p)
{
/*Not supported*/
LV_UNUSED(mon_p);
return;
}
lv_result_t lv_mem_test_core(void)
{
/*Not supported*/
return LV_RESULT_OK;
}
/**********************
* STATIC FUNCTIONS
**********************/
#endif /*LV_USE_BUILTIN_MALLOC*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/stdlib | repos/zig_workbench/BaseLVGL/lib/lvgl/src/stdlib/clib/lv_string_clib.c | /**
* @file lv_string.c
*/
/*********************
* INCLUDES
*********************/
#include "../../lv_conf_internal.h"
#if LV_USE_STDLIB_STRING == LV_STDLIB_CLIB
#include "../lv_string.h"
#include <string.h>
#if LV_USE_STDLIB_MALLOC == LV_STDLIB_BUILTIN
#include "../lv_mem.h"
#endif
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
LV_ATTRIBUTE_FAST_MEM void * lv_memcpy(void * dst, const void * src, size_t len)
{
return memcpy(dst, src, len);
}
LV_ATTRIBUTE_FAST_MEM void lv_memset(void * dst, uint8_t v, size_t len)
{
memset(dst, v, len);
}
size_t lv_strlen(const char * str)
{
return strlen(str);
}
char * lv_strncpy(char * dst, const char * src, size_t dest_size)
{
if(dest_size > 0) {
dst[0] = '\0';
strncat(dst, src, dest_size - 1);
}
return dst;
}
char * lv_strcpy(char * dst, const char * src)
{
return strcpy(dst, src);
}
char * lv_strdup(const char * src)
{
/*strdup uses malloc, so use the built in malloc if it's enabled */
#if LV_USE_STDLIB_MALLOC == LV_STDLIB_BUILTIN
size_t len = lv_strlen(src) + 1;
char * dst = lv_malloc(len);
if(dst == NULL) return NULL;
lv_memcpy(dst, src, len); /*do memcpy is faster than strncpy when length is known*/
return dst;
#else
return strdup(src);
#endif
}
/**********************
* STATIC FUNCTIONS
**********************/
#endif /*LV_USE_BUILTIN_MEMCPY*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/stdlib | repos/zig_workbench/BaseLVGL/lib/lvgl/src/stdlib/clib/lv_sprintf_clib.c |
/**
* @file lv_templ.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../lv_conf_internal.h"
#if LV_USE_STDLIB_SPRINTF == LV_STDLIB_CLIB
#include <stdio.h>
#include <stdarg.h>
#include "../lv_sprintf.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
int lv_snprintf(char * buffer, size_t count, const char * format, ...)
{
va_list va;
va_start(va, format);
const int ret = vsnprintf(buffer, count, format, va);
va_end(va);
return ret;
}
int lv_vsnprintf(char * buffer, size_t count, const char * format, va_list va)
{
return vsnprintf(buffer, count, format, va);
}
/**********************
* STATIC FUNCTIONS
**********************/
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/tick/lv_tick.h | /**
* @file lv_hal_tick.h
* Provide access to the system tick with 1 millisecond resolution
*/
#ifndef LV_HAL_TICK_H
#define LV_HAL_TICK_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#include <stdint.h>
#include <stdbool.h>
/*********************
* DEFINES
*********************/
#ifndef LV_ATTRIBUTE_TICK_INC
#define LV_ATTRIBUTE_TICK_INC
#endif
/**********************
* TYPEDEFS
**********************/
typedef uint32_t (*lv_tick_get_cb_t)(void);
typedef struct {
uint32_t sys_time;
volatile uint8_t sys_irq_flag;
lv_tick_get_cb_t tick_get_cb;
} lv_tick_state_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* You have to call this function periodically
* @param tick_period the call period of this function in milliseconds
*/
LV_ATTRIBUTE_TICK_INC void lv_tick_inc(uint32_t tick_period);
/**
* Get the elapsed milliseconds since start up
* @return the elapsed milliseconds
*/
uint32_t lv_tick_get(void);
/**
* Get the elapsed milliseconds since a previous time stamp
* @param prev_tick a previous time stamp (return value of lv_tick_get() )
* @return the elapsed milliseconds since 'prev_tick'
*/
uint32_t lv_tick_elaps(uint32_t prev_tick);
/**
* Set the custom callback for 'lv_tick_get'
* @param cb call this callback on 'lv_tick_get'
*/
void lv_tick_set_cb(lv_tick_get_cb_t cb);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_HAL_TICK_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/tick/lv_tick.c | /**
* @file lv_tick.c
* Provide access to the system tick with 1 millisecond resolution
*/
/*********************
* INCLUDES
*********************/
#include "lv_tick.h"
#include <stddef.h>
#include "../core/lv_global.h"
/*********************
* DEFINES
*********************/
#define state LV_GLOBAL_DEFAULT()->tick_state
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* You have to call this function periodically
* @param tick_period the call period of this function in milliseconds
*/
LV_ATTRIBUTE_TICK_INC void lv_tick_inc(uint32_t tick_period)
{
lv_tick_state_t * state_p = &state;
state_p->sys_irq_flag = 0;
state_p->sys_time += tick_period;
}
/**
* Get the elapsed milliseconds since start up
* @return the elapsed milliseconds
*/
uint32_t lv_tick_get(void)
{
lv_tick_state_t * state_p = &state;
if(state_p->tick_get_cb)
return state_p->tick_get_cb();
/*If `lv_tick_inc` is called from an interrupt while `sys_time` is read
*the result might be corrupted.
*This loop detects if `lv_tick_inc` was called while reading `sys_time`.
*If `tick_irq_flag` was cleared in `lv_tick_inc` try to read again
*until `tick_irq_flag` remains `1`.*/
uint32_t result;
do {
state_p->sys_irq_flag = 1;
result = state_p->sys_time;
} while(!state_p->sys_irq_flag); /*Continue until see a non interrupted cycle*/
return result;
}
/**
* Get the elapsed milliseconds since a previous time stamp
* @param prev_tick a previous time stamp (return value of lv_tick_get() )
* @return the elapsed milliseconds since 'prev_tick'
*/
uint32_t lv_tick_elaps(uint32_t prev_tick)
{
uint32_t act_time = lv_tick_get();
/*If there is no overflow in sys_time simple subtract*/
if(act_time >= prev_tick) {
prev_tick = act_time - prev_tick;
}
else {
prev_tick = UINT32_MAX - prev_tick + 1;
prev_tick += act_time;
}
return prev_tick;
}
void lv_tick_set_cb(lv_tick_get_cb_t cb)
{
state.tick_get_cb = cb;
}
/**********************
* STATIC FUNCTIONS
**********************/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/freetype/ftoption.h | /****************************************************************************
*
* ftoption.h
*
* User-selectable configuration macros (specification only).
*
* Copyright (C) 1996-2022 by
* David Turner, Robert Wilhelm, and Werner Lemberg.
*
* This file is part of the FreeType project, and may only be used,
* modified, and distributed under the terms of the FreeType project
* license, LICENSE.TXT. By continuing to use, modify, or distribute
* this file you indicate that you have read the license and
* understand and accept it fully.
*
*/
#ifndef FTOPTION_H_
#define FTOPTION_H_
#include <ft2build.h>
FT_BEGIN_HEADER
/**************************************************************************
*
* USER-SELECTABLE CONFIGURATION MACROS
*
* This file contains the default configuration macro definitions for a
* standard build of the FreeType library. There are three ways to use
* this file to build project-specific versions of the library:
*
* - You can modify this file by hand, but this is not recommended in
* cases where you would like to build several versions of the library
* from a single source directory.
*
* - You can put a copy of this file in your build directory, more
* precisely in `$BUILD/freetype/config/ftoption.h`, where `$BUILD` is
* the name of a directory that is included _before_ the FreeType include
* path during compilation.
*
* The default FreeType Makefiles use the build directory
* `builds/<system>` by default, but you can easily change that for your
* own projects.
*
* - Copy the file <ft2build.h> to `$BUILD/ft2build.h` and modify it
* slightly to pre-define the macro `FT_CONFIG_OPTIONS_H` used to locate
* this file during the build. For example,
*
* ```
* #define FT_CONFIG_OPTIONS_H <myftoptions.h>
* #include <freetype/config/ftheader.h>
* ```
*
* will use `$BUILD/myftoptions.h` instead of this file for macro
* definitions.
*
* Note also that you can similarly pre-define the macro
* `FT_CONFIG_MODULES_H` used to locate the file listing of the modules
* that are statically linked to the library at compile time. By
* default, this file is `<freetype/config/ftmodule.h>`.
*
* We highly recommend using the third method whenever possible.
*
*/
/*************************************************************************/
/*************************************************************************/
/**** ****/
/**** G E N E R A L F R E E T Y P E 2 C O N F I G U R A T I O N ****/
/**** ****/
/*************************************************************************/
/*************************************************************************/
/*#************************************************************************
*
* If you enable this configuration option, FreeType recognizes an
* environment variable called `FREETYPE_PROPERTIES`, which can be used to
* control the various font drivers and modules. The controllable
* properties are listed in the section @properties.
*
* You have to undefine this configuration option on platforms that lack
* the concept of environment variables (and thus don't have the `getenv`
* function), for example Windows CE.
*
* `FREETYPE_PROPERTIES` has the following syntax form (broken here into
* multiple lines for better readability).
*
* ```
* <optional whitespace>
* <module-name1> ':'
* <property-name1> '=' <property-value1>
* <whitespace>
* <module-name2> ':'
* <property-name2> '=' <property-value2>
* ...
* ```
*
* Example:
*
* ```
* FREETYPE_PROPERTIES=truetype:interpreter-version=35 \
* cff:no-stem-darkening=1
* ```
*
*/
#define FT_CONFIG_OPTION_ENVIRONMENT_PROPERTIES
/**************************************************************************
*
* Uncomment the line below if you want to activate LCD rendering
* technology similar to ClearType in this build of the library. This
* technology triples the resolution in the direction color subpixels. To
* mitigate color fringes inherent to this technology, you also need to
* explicitly set up LCD filtering.
*
* When this macro is not defined, FreeType offers alternative LCD
* rendering technology that produces excellent output.
*/
/* #define FT_CONFIG_OPTION_SUBPIXEL_RENDERING */
/**************************************************************************
*
* Many compilers provide a non-ANSI 64-bit data type that can be used by
* FreeType to speed up some computations. However, this will create some
* problems when compiling the library in strict ANSI mode.
*
* For this reason, the use of 64-bit integers is normally disabled when
* the `__STDC__` macro is defined. You can however disable this by
* defining the macro `FT_CONFIG_OPTION_FORCE_INT64` here.
*
* For most compilers, this will only create compilation warnings when
* building the library.
*
* ObNote: The compiler-specific 64-bit integers are detected in the
* file `ftconfig.h` either statically or through the `configure`
* script on supported platforms.
*/
#undef FT_CONFIG_OPTION_FORCE_INT64
/**************************************************************************
*
* If this macro is defined, do not try to use an assembler version of
* performance-critical functions (e.g., @FT_MulFix). You should only do
* that to verify that the assembler function works properly, or to execute
* benchmark tests of the various implementations.
*/
/* #define FT_CONFIG_OPTION_NO_ASSEMBLER */
/**************************************************************************
*
* If this macro is defined, try to use an inlined assembler version of the
* @FT_MulFix function, which is a 'hotspot' when loading and hinting
* glyphs, and which should be executed as fast as possible.
*
* Note that if your compiler or CPU is not supported, this will default to
* the standard and portable implementation found in `ftcalc.c`.
*/
#define FT_CONFIG_OPTION_INLINE_MULFIX
/**************************************************************************
*
* LZW-compressed file support.
*
* FreeType now handles font files that have been compressed with the
* `compress` program. This is mostly used to parse many of the PCF
* files that come with various X11 distributions. The implementation
* uses NetBSD's `zopen` to partially uncompress the file on the fly (see
* `src/lzw/ftgzip.c`).
*
* Define this macro if you want to enable this 'feature'.
*/
#define FT_CONFIG_OPTION_USE_LZW
/**************************************************************************
*
* Gzip-compressed file support.
*
* FreeType now handles font files that have been compressed with the
* `gzip` program. This is mostly used to parse many of the PCF files
* that come with XFree86. The implementation uses 'zlib' to partially
* uncompress the file on the fly (see `src/gzip/ftgzip.c`).
*
* Define this macro if you want to enable this 'feature'. See also the
* macro `FT_CONFIG_OPTION_SYSTEM_ZLIB` below.
*/
#define FT_CONFIG_OPTION_USE_ZLIB
/**************************************************************************
*
* ZLib library selection
*
* This macro is only used when `FT_CONFIG_OPTION_USE_ZLIB` is defined.
* It allows FreeType's 'ftgzip' component to link to the system's
* installation of the ZLib library. This is useful on systems like
* Unix or VMS where it generally is already available.
*
* If you let it undefined, the component will use its own copy of the
* zlib sources instead. These have been modified to be included
* directly within the component and **not** export external function
* names. This allows you to link any program with FreeType _and_ ZLib
* without linking conflicts.
*
* Do not `#undef` this macro here since the build system might define
* it for certain configurations only.
*
* If you use a build system like cmake or the `configure` script,
* options set by those programs have precedence, overwriting the value
* here with the configured one.
*
* If you use the GNU make build system directly (that is, without the
* `configure` script) and you define this macro, you also have to pass
* `SYSTEM_ZLIB=yes` as an argument to make.
*/
/* #define FT_CONFIG_OPTION_SYSTEM_ZLIB */
/**************************************************************************
*
* Bzip2-compressed file support.
*
* FreeType now handles font files that have been compressed with the
* `bzip2` program. This is mostly used to parse many of the PCF files
* that come with XFree86. The implementation uses `libbz2` to partially
* uncompress the file on the fly (see `src/bzip2/ftbzip2.c`). Contrary
* to gzip, bzip2 currently is not included and need to use the system
* available bzip2 implementation.
*
* Define this macro if you want to enable this 'feature'.
*
* If you use a build system like cmake or the `configure` script,
* options set by those programs have precedence, overwriting the value
* here with the configured one.
*/
/* #define FT_CONFIG_OPTION_USE_BZIP2 */
/**************************************************************************
*
* Define to disable the use of file stream functions and types, `FILE`,
* `fopen`, etc. Enables the use of smaller system libraries on embedded
* systems that have multiple system libraries, some with or without file
* stream support, in the cases where file stream support is not necessary
* such as memory loading of font files.
*/
/* #define FT_CONFIG_OPTION_DISABLE_STREAM_SUPPORT */
/**************************************************************************
*
* PNG bitmap support.
*
* FreeType now handles loading color bitmap glyphs in the PNG format.
* This requires help from the external libpng library. Uncompressed
* color bitmaps do not need any external libraries and will be supported
* regardless of this configuration.
*
* Define this macro if you want to enable this 'feature'.
*
* If you use a build system like cmake or the `configure` script,
* options set by those programs have precedence, overwriting the value
* here with the configured one.
*/
/* #define FT_CONFIG_OPTION_USE_PNG */
/**************************************************************************
*
* HarfBuzz support.
*
* FreeType uses the HarfBuzz library to improve auto-hinting of OpenType
* fonts. If available, many glyphs not directly addressable by a font's
* character map will be hinted also.
*
* Define this macro if you want to enable this 'feature'.
*
* If you use a build system like cmake or the `configure` script,
* options set by those programs have precedence, overwriting the value
* here with the configured one.
*/
/* #define FT_CONFIG_OPTION_USE_HARFBUZZ */
/**************************************************************************
*
* Brotli support.
*
* FreeType uses the Brotli library to provide support for decompressing
* WOFF2 streams.
*
* Define this macro if you want to enable this 'feature'.
*
* If you use a build system like cmake or the `configure` script,
* options set by those programs have precedence, overwriting the value
* here with the configured one.
*/
/* #define FT_CONFIG_OPTION_USE_BROTLI */
/**************************************************************************
*
* Glyph Postscript Names handling
*
* By default, FreeType 2 is compiled with the 'psnames' module. This
* module is in charge of converting a glyph name string into a Unicode
* value, or return a Macintosh standard glyph name for the use with the
* TrueType 'post' table.
*
* Undefine this macro if you do not want 'psnames' compiled in your
* build of FreeType. This has the following effects:
*
* - The TrueType driver will provide its own set of glyph names, if you
* build it to support postscript names in the TrueType 'post' table,
* but will not synthesize a missing Unicode charmap.
*
* - The Type~1 driver will not be able to synthesize a Unicode charmap
* out of the glyphs found in the fonts.
*
* You would normally undefine this configuration macro when building a
* version of FreeType that doesn't contain a Type~1 or CFF driver.
*/
#define FT_CONFIG_OPTION_POSTSCRIPT_NAMES
/**************************************************************************
*
* Postscript Names to Unicode Values support
*
* By default, FreeType~2 is built with the 'psnames' module compiled in.
* Among other things, the module is used to convert a glyph name into a
* Unicode value. This is especially useful in order to synthesize on
* the fly a Unicode charmap from the CFF/Type~1 driver through a big
* table named the 'Adobe Glyph List' (AGL).
*
* Undefine this macro if you do not want the Adobe Glyph List compiled
* in your 'psnames' module. The Type~1 driver will not be able to
* synthesize a Unicode charmap out of the glyphs found in the fonts.
*/
#define FT_CONFIG_OPTION_ADOBE_GLYPH_LIST
/**************************************************************************
*
* Support for Mac fonts
*
* Define this macro if you want support for outline fonts in Mac format
* (mac dfont, mac resource, macbinary containing a mac resource) on
* non-Mac platforms.
*
* Note that the 'FOND' resource isn't checked.
*/
/* #define FT_CONFIG_OPTION_MAC_FONTS */
/**************************************************************************
*
* Guessing methods to access embedded resource forks
*
* Enable extra Mac fonts support on non-Mac platforms (e.g., GNU/Linux).
*
* Resource forks which include fonts data are stored sometimes in
* locations which users or developers don't expected. In some cases,
* resource forks start with some offset from the head of a file. In
* other cases, the actual resource fork is stored in file different from
* what the user specifies. If this option is activated, FreeType tries
* to guess whether such offsets or different file names must be used.
*
* Note that normal, direct access of resource forks is controlled via
* the `FT_CONFIG_OPTION_MAC_FONTS` option.
*/
#ifdef FT_CONFIG_OPTION_MAC_FONTS
#define FT_CONFIG_OPTION_GUESSING_EMBEDDED_RFORK
#endif
/**************************************************************************
*
* Allow the use of `FT_Incremental_Interface` to load typefaces that
* contain no glyph data, but supply it via a callback function. This is
* required by clients supporting document formats which supply font data
* incrementally as the document is parsed, such as the Ghostscript
* interpreter for the PostScript language.
*/
#define FT_CONFIG_OPTION_INCREMENTAL
/**************************************************************************
*
* The size in bytes of the render pool used by the scan-line converter to
* do all of its work.
*/
#define FT_RENDER_POOL_SIZE 16384L
/**************************************************************************
*
* FT_MAX_MODULES
*
* The maximum number of modules that can be registered in a single
* FreeType library object. 32~is the default.
*/
#define FT_MAX_MODULES 32
/**************************************************************************
*
* Debug level
*
* FreeType can be compiled in debug or trace mode. In debug mode,
* errors are reported through the 'ftdebug' component. In trace mode,
* additional messages are sent to the standard output during execution.
*
* Define `FT_DEBUG_LEVEL_ERROR` to build the library in debug mode.
* Define `FT_DEBUG_LEVEL_TRACE` to build it in trace mode.
*
* Don't define any of these macros to compile in 'release' mode!
*
* Do not `#undef` these macros here since the build system might define
* them for certain configurations only.
*/
/* #define FT_DEBUG_LEVEL_ERROR */
/* #define FT_DEBUG_LEVEL_TRACE */
/**************************************************************************
*
* Logging
*
* Compiling FreeType in debug or trace mode makes FreeType write error
* and trace log messages to `stderr`. Enabling this macro
* automatically forces the `FT_DEBUG_LEVEL_ERROR` and
* `FT_DEBUG_LEVEL_TRACE` macros and allows FreeType to write error and
* trace log messages to a file instead of `stderr`. For writing logs
* to a file, FreeType uses an the external `dlg` library (the source
* code is in `src/dlg`).
*
* This option needs a C99 compiler.
*/
/* #define FT_DEBUG_LOGGING */
/**************************************************************************
*
* Autofitter debugging
*
* If `FT_DEBUG_AUTOFIT` is defined, FreeType provides some means to
* control the autofitter behaviour for debugging purposes with global
* boolean variables (consequently, you should **never** enable this
* while compiling in 'release' mode):
*
* ```
* _af_debug_disable_horz_hints
* _af_debug_disable_vert_hints
* _af_debug_disable_blue_hints
* ```
*
* Additionally, the following functions provide dumps of various
* internal autofit structures to stdout (using `printf`):
*
* ```
* af_glyph_hints_dump_points
* af_glyph_hints_dump_segments
* af_glyph_hints_dump_edges
* af_glyph_hints_get_num_segments
* af_glyph_hints_get_segment_offset
* ```
*
* As an argument, they use another global variable:
*
* ```
* _af_debug_hints
* ```
*
* Please have a look at the `ftgrid` demo program to see how those
* variables and macros should be used.
*
* Do not `#undef` these macros here since the build system might define
* them for certain configurations only.
*/
/* #define FT_DEBUG_AUTOFIT */
/**************************************************************************
*
* Memory Debugging
*
* FreeType now comes with an integrated memory debugger that is capable
* of detecting simple errors like memory leaks or double deletes. To
* compile it within your build of the library, you should define
* `FT_DEBUG_MEMORY` here.
*
* Note that the memory debugger is only activated at runtime when when
* the _environment_ variable `FT2_DEBUG_MEMORY` is defined also!
*
* Do not `#undef` this macro here since the build system might define it
* for certain configurations only.
*/
/* #define FT_DEBUG_MEMORY */
/**************************************************************************
*
* Module errors
*
* If this macro is set (which is _not_ the default), the higher byte of
* an error code gives the module in which the error has occurred, while
* the lower byte is the real error code.
*
* Setting this macro makes sense for debugging purposes only, since it
* would break source compatibility of certain programs that use
* FreeType~2.
*
* More details can be found in the files `ftmoderr.h` and `fterrors.h`.
*/
#undef FT_CONFIG_OPTION_USE_MODULE_ERRORS
/**************************************************************************
*
* OpenType SVG Glyph Support
*
* Setting this macro enables support for OpenType SVG glyphs. By
* default, FreeType can only fetch SVG documents. However, it can also
* render them if external rendering hook functions are plugged in at
* runtime.
*
* More details on the hooks can be found in file `otsvg.h`.
*/
#define FT_CONFIG_OPTION_SVG
/**************************************************************************
*
* Error Strings
*
* If this macro is set, `FT_Error_String` will return meaningful
* descriptions. This is not enabled by default to reduce the overall
* size of FreeType.
*
* More details can be found in the file `fterrors.h`.
*/
#define FT_CONFIG_OPTION_ERROR_STRINGS
/*************************************************************************/
/*************************************************************************/
/**** ****/
/**** S F N T D R I V E R C O N F I G U R A T I O N ****/
/**** ****/
/*************************************************************************/
/*************************************************************************/
/**************************************************************************
*
* Define `TT_CONFIG_OPTION_EMBEDDED_BITMAPS` if you want to support
* embedded bitmaps in all formats using the 'sfnt' module (namely
* TrueType~& OpenType).
*/
#define TT_CONFIG_OPTION_EMBEDDED_BITMAPS
/**************************************************************************
*
* Define `TT_CONFIG_OPTION_COLOR_LAYERS` if you want to support colored
* outlines (from the 'COLR'/'CPAL' tables) in all formats using the 'sfnt'
* module (namely TrueType~& OpenType).
*/
#define TT_CONFIG_OPTION_COLOR_LAYERS
/**************************************************************************
*
* Define `TT_CONFIG_OPTION_POSTSCRIPT_NAMES` if you want to be able to
* load and enumerate the glyph Postscript names in a TrueType or OpenType
* file.
*
* Note that when you do not compile the 'psnames' module by undefining the
* above `FT_CONFIG_OPTION_POSTSCRIPT_NAMES`, the 'sfnt' module will
* contain additional code used to read the PS Names table from a font.
*
* (By default, the module uses 'psnames' to extract glyph names.)
*/
#define TT_CONFIG_OPTION_POSTSCRIPT_NAMES
/**************************************************************************
*
* Define `TT_CONFIG_OPTION_SFNT_NAMES` if your applications need to access
* the internal name table in a SFNT-based format like TrueType or
* OpenType. The name table contains various strings used to describe the
* font, like family name, copyright, version, etc. It does not contain
* any glyph name though.
*
* Accessing SFNT names is done through the functions declared in
* `ftsnames.h`.
*/
#define TT_CONFIG_OPTION_SFNT_NAMES
/**************************************************************************
*
* TrueType CMap support
*
* Here you can fine-tune which TrueType CMap table format shall be
* supported.
*/
#define TT_CONFIG_CMAP_FORMAT_0
#define TT_CONFIG_CMAP_FORMAT_2
#define TT_CONFIG_CMAP_FORMAT_4
#define TT_CONFIG_CMAP_FORMAT_6
#define TT_CONFIG_CMAP_FORMAT_8
#define TT_CONFIG_CMAP_FORMAT_10
#define TT_CONFIG_CMAP_FORMAT_12
#define TT_CONFIG_CMAP_FORMAT_13
#define TT_CONFIG_CMAP_FORMAT_14
/*************************************************************************/
/*************************************************************************/
/**** ****/
/**** T R U E T Y P E D R I V E R C O N F I G U R A T I O N ****/
/**** ****/
/*************************************************************************/
/*************************************************************************/
/**************************************************************************
*
* Define `TT_CONFIG_OPTION_BYTECODE_INTERPRETER` if you want to compile a
* bytecode interpreter in the TrueType driver.
*
* By undefining this, you will only compile the code necessary to load
* TrueType glyphs without hinting.
*
* Do not `#undef` this macro here, since the build system might define it
* for certain configurations only.
*/
#define TT_CONFIG_OPTION_BYTECODE_INTERPRETER
/**************************************************************************
*
* Define `TT_CONFIG_OPTION_SUBPIXEL_HINTING` if you want to compile
* subpixel hinting support into the TrueType driver. This modifies the
* TrueType hinting mechanism when anything but `FT_RENDER_MODE_MONO` is
* requested.
*
* In particular, it modifies the bytecode interpreter to interpret (or
* not) instructions in a certain way so that all TrueType fonts look like
* they do in a Windows ClearType (DirectWrite) environment. See [1] for a
* technical overview on what this means. See `ttinterp.h` for more
* details on the LEAN option.
*
* There are three possible values.
*
* Value 1:
* This value is associated with the 'Infinality' moniker, contributed by
* an individual nicknamed Infinality with the goal of making TrueType
* fonts render better than on Windows. A high amount of configurability
* and flexibility, down to rules for single glyphs in fonts, but also
* very slow. Its experimental and slow nature and the original
* developer losing interest meant that this option was never enabled in
* default builds.
*
* The corresponding interpreter version is v38.
*
* Value 2:
* The new default mode for the TrueType driver. The Infinality code
* base was stripped to the bare minimum and all configurability removed
* in the name of speed and simplicity. The configurability was mainly
* aimed at legacy fonts like 'Arial', 'Times New Roman', or 'Courier'.
* Legacy fonts are fonts that modify vertical stems to achieve clean
* black-and-white bitmaps. The new mode focuses on applying a minimal
* set of rules to all fonts indiscriminately so that modern and web
* fonts render well while legacy fonts render okay.
*
* The corresponding interpreter version is v40.
*
* Value 3:
* Compile both, making both v38 and v40 available (the latter is the
* default).
*
* By undefining these, you get rendering behavior like on Windows without
* ClearType, i.e., Windows XP without ClearType enabled and Win9x
* (interpreter version v35). Or not, depending on how much hinting blood
* and testing tears the font designer put into a given font. If you
* define one or both subpixel hinting options, you can switch between
* between v35 and the ones you define (using `FT_Property_Set`).
*
* This option requires `TT_CONFIG_OPTION_BYTECODE_INTERPRETER` to be
* defined.
*
* [1]
* https://www.microsoft.com/typography/cleartype/truetypecleartype.aspx
*/
/* #define TT_CONFIG_OPTION_SUBPIXEL_HINTING 1 */
#define TT_CONFIG_OPTION_SUBPIXEL_HINTING 2
/* #define TT_CONFIG_OPTION_SUBPIXEL_HINTING ( 1 | 2 ) */
/**************************************************************************
*
* Define `TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED` to compile the
* TrueType glyph loader to use Apple's definition of how to handle
* component offsets in composite glyphs.
*
* Apple and MS disagree on the default behavior of component offsets in
* composites. Apple says that they should be scaled by the scaling
* factors in the transformation matrix (roughly, it's more complex) while
* MS says they should not. OpenType defines two bits in the composite
* flags array which can be used to disambiguate, but old fonts will not
* have them.
*
* https://www.microsoft.com/typography/otspec/glyf.htm
* https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6glyf.html
*/
#undef TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED
/**************************************************************************
*
* Define `TT_CONFIG_OPTION_GX_VAR_SUPPORT` if you want to include support
* for Apple's distortable font technology ('fvar', 'gvar', 'cvar', and
* 'avar' tables). Tagged 'Font Variations', this is now part of OpenType
* also. This has many similarities to Type~1 Multiple Masters support.
*/
#define TT_CONFIG_OPTION_GX_VAR_SUPPORT
/**************************************************************************
*
* Define `TT_CONFIG_OPTION_BDF` if you want to include support for an
* embedded 'BDF~' table within SFNT-based bitmap formats.
*/
#define TT_CONFIG_OPTION_BDF
/**************************************************************************
*
* Option `TT_CONFIG_OPTION_MAX_RUNNABLE_OPCODES` controls the maximum
* number of bytecode instructions executed for a single run of the
* bytecode interpreter, needed to prevent infinite loops. You don't want
* to change this except for very special situations (e.g., making a
* library fuzzer spend less time to handle broken fonts).
*
* It is not expected that this value is ever modified by a configuring
* script; instead, it gets surrounded with `#ifndef ... #endif` so that
* the value can be set as a preprocessor option on the compiler's command
* line.
*/
#ifndef TT_CONFIG_OPTION_MAX_RUNNABLE_OPCODES
#define TT_CONFIG_OPTION_MAX_RUNNABLE_OPCODES 1000000L
#endif
/*************************************************************************/
/*************************************************************************/
/**** ****/
/**** T Y P E 1 D R I V E R C O N F I G U R A T I O N ****/
/**** ****/
/*************************************************************************/
/*************************************************************************/
/**************************************************************************
*
* `T1_MAX_DICT_DEPTH` is the maximum depth of nest dictionaries and arrays
* in the Type~1 stream (see `t1load.c`). A minimum of~4 is required.
*/
#define T1_MAX_DICT_DEPTH 5
/**************************************************************************
*
* `T1_MAX_SUBRS_CALLS` details the maximum number of nested sub-routine
* calls during glyph loading.
*/
#define T1_MAX_SUBRS_CALLS 16
/**************************************************************************
*
* `T1_MAX_CHARSTRING_OPERANDS` is the charstring stack's capacity. A
* minimum of~16 is required.
*
* The Chinese font 'MingTiEG-Medium' (covering the CNS 11643 character
* set) needs 256.
*/
#define T1_MAX_CHARSTRINGS_OPERANDS 256
/**************************************************************************
*
* Define this configuration macro if you want to prevent the compilation
* of the 't1afm' module, which is in charge of reading Type~1 AFM files
* into an existing face. Note that if set, the Type~1 driver will be
* unable to produce kerning distances.
*/
#undef T1_CONFIG_OPTION_NO_AFM
/**************************************************************************
*
* Define this configuration macro if you want to prevent the compilation
* of the Multiple Masters font support in the Type~1 driver.
*/
#undef T1_CONFIG_OPTION_NO_MM_SUPPORT
/**************************************************************************
*
* `T1_CONFIG_OPTION_OLD_ENGINE` controls whether the pre-Adobe Type~1
* engine gets compiled into FreeType. If defined, it is possible to
* switch between the two engines using the `hinting-engine` property of
* the 'type1' driver module.
*/
/* #define T1_CONFIG_OPTION_OLD_ENGINE */
/*************************************************************************/
/*************************************************************************/
/**** ****/
/**** C F F D R I V E R C O N F I G U R A T I O N ****/
/**** ****/
/*************************************************************************/
/*************************************************************************/
/**************************************************************************
*
* Using `CFF_CONFIG_OPTION_DARKENING_PARAMETER_{X,Y}{1,2,3,4}` it is
* possible to set up the default values of the four control points that
* define the stem darkening behaviour of the (new) CFF engine. For more
* details please read the documentation of the `darkening-parameters`
* property (file `ftdriver.h`), which allows the control at run-time.
*
* Do **not** undefine these macros!
*/
#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_X1 500
#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y1 400
#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_X2 1000
#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y2 275
#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_X3 1667
#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y3 275
#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_X4 2333
#define CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y4 0
/**************************************************************************
*
* `CFF_CONFIG_OPTION_OLD_ENGINE` controls whether the pre-Adobe CFF engine
* gets compiled into FreeType. If defined, it is possible to switch
* between the two engines using the `hinting-engine` property of the 'cff'
* driver module.
*/
/* #define CFF_CONFIG_OPTION_OLD_ENGINE */
/*************************************************************************/
/*************************************************************************/
/**** ****/
/**** P C F D R I V E R C O N F I G U R A T I O N ****/
/**** ****/
/*************************************************************************/
/*************************************************************************/
/**************************************************************************
*
* There are many PCF fonts just called 'Fixed' which look completely
* different, and which have nothing to do with each other. When selecting
* 'Fixed' in KDE or Gnome one gets results that appear rather random, the
* style changes often if one changes the size and one cannot select some
* fonts at all. This option makes the 'pcf' module prepend the foundry
* name (plus a space) to the family name.
*
* We also check whether we have 'wide' characters; all put together, we
* get family names like 'Sony Fixed' or 'Misc Fixed Wide'.
*
* If this option is activated, it can be controlled with the
* `no-long-family-names` property of the 'pcf' driver module.
*/
/* #define PCF_CONFIG_OPTION_LONG_FAMILY_NAMES */
/*************************************************************************/
/*************************************************************************/
/**** ****/
/**** A U T O F I T M O D U L E C O N F I G U R A T I O N ****/
/**** ****/
/*************************************************************************/
/*************************************************************************/
/**************************************************************************
*
* Compile 'autofit' module with CJK (Chinese, Japanese, Korean) script
* support.
*/
#define AF_CONFIG_OPTION_CJK
/**************************************************************************
*
* Compile 'autofit' module with fallback Indic script support, covering
* some scripts that the 'latin' submodule of the 'autofit' module doesn't
* (yet) handle. Currently, this needs option `AF_CONFIG_OPTION_CJK`.
*/
#ifdef AF_CONFIG_OPTION_CJK
#define AF_CONFIG_OPTION_INDIC
#endif
/**************************************************************************
*
* Use TrueType-like size metrics for 'light' auto-hinting.
*
* It is strongly recommended to avoid this option, which exists only to
* help some legacy applications retain its appearance and behaviour with
* respect to auto-hinted TrueType fonts.
*
* The very reason this option exists at all are GNU/Linux distributions
* like Fedora that did not un-patch the following change (which was
* present in FreeType between versions 2.4.6 and 2.7.1, inclusive).
*
* ```
* 2011-07-16 Steven Chu <[email protected]>
*
* [truetype] Fix metrics on size request for scalable fonts.
* ```
*
* This problematic commit is now reverted (more or less).
*/
/* #define AF_CONFIG_OPTION_TT_SIZE_METRICS */
/* */
/*
* This macro is obsolete. Support has been removed in FreeType version
* 2.5.
*/
/* #define FT_CONFIG_OPTION_OLD_INTERNALS */
/*
* The next three macros are defined if native TrueType hinting is
* requested by the definitions above. Don't change this.
*/
#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
#define TT_USE_BYTECODE_INTERPRETER
#ifdef TT_CONFIG_OPTION_SUBPIXEL_HINTING
#if TT_CONFIG_OPTION_SUBPIXEL_HINTING & 1
#define TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY
#endif
#if TT_CONFIG_OPTION_SUBPIXEL_HINTING & 2
#define TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL
#endif
#endif
#endif
/*
* The TT_SUPPORT_COLRV1 macro is defined to indicate to clients that this
* version of FreeType has support for 'COLR' v1 API. This definition is
* useful to FreeType clients that want to build in support for 'COLR' v1
* depending on a tip-of-tree checkout before it is officially released in
* FreeType, and while the feature cannot yet be tested against using
* version macros. Don't change this macro. This may be removed once the
* feature is in a FreeType release version and version macros can be used
* to test for availability.
*/
#ifdef TT_CONFIG_OPTION_COLOR_LAYERS
#define TT_SUPPORT_COLRV1
#endif
/*
* Check CFF darkening parameters. The checks are the same as in function
* `cff_property_set` in file `cffdrivr.c`.
*/
#if CFF_CONFIG_OPTION_DARKENING_PARAMETER_X1 < 0 || \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_X2 < 0 || \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_X3 < 0 || \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_X4 < 0 || \
\
CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y1 < 0 || \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y2 < 0 || \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y3 < 0 || \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y4 < 0 || \
\
CFF_CONFIG_OPTION_DARKENING_PARAMETER_X1 > \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_X2 || \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_X2 > \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_X3 || \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_X3 > \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_X4 || \
\
CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y1 > 500 || \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y2 > 500 || \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y3 > 500 || \
CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y4 > 500
#error "Invalid CFF darkening parameters!"
#endif
FT_END_HEADER
#endif /* FTOPTION_H_ */
/* END */
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/freetype/lv_freetype.h | /**
* @file lv_freetype.h
*
*/
#ifndef LV_FREETYPE_H
#define LV_FREETYPE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_FREETYPE
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef enum {
LV_FREETYPE_FONT_STYLE_NORMAL = 0,
LV_FREETYPE_FONT_STYLE_ITALIC = 1 << 0,
LV_FREETYPE_FONT_STYLE_BOLD = 1 << 1
} lv_freetype_font_style_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Initialize the freetype library.
* @param max_faces Maximum number of opened FT_Face objects managed by this cache instance. Use 0 for defaults.
* @param max_sizes Maximum number of opened FT_Size objects managed by this cache instance. Use 0 for defaults.
* @param max_bytes Maximum number of bytes to use for cached data nodes. Use 0 for defaults.
* Note that this value does not account for managed FT_Face and FT_Size objects.
* @return LV_RESULT_OK on success, otherwise LV_RESULT_INVALID.
*/
lv_result_t lv_freetype_init(uint16_t max_faces, uint16_t max_sizes, uint32_t max_bytes);
/**
* Uninitialize the freetype library
*/
void lv_freetype_uninit(void);
/**
* Create a freetype font.
* @param pathname font file path.
* @param size font size.
* @param style font style(see lv_freetype_font_style_t for details).
* @return Created font, or NULL on failure.
*/
lv_font_t * lv_freetype_font_create(const char * pathname, uint16_t size, uint16_t style);
/**
* Delete a freetype font.
* @param font freetype font to be deleted.
*/
void lv_freetype_font_delete(lv_font_t * font);
/**********************
* MACROS
**********************/
#endif /*LV_USE_FREETYPE*/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* LV_FREETYPE_H */
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/freetype/lv_freetype.c | /**
* @file lv_freetype.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_freetype.h"
#if LV_USE_FREETYPE
#include "ft2build.h"
#include FT_FREETYPE_H
#include FT_GLYPH_H
#include FT_CACHE_H
#include FT_SIZES_H
#include FT_IMAGE_H
#include FT_OUTLINE_H
#include "../../core/lv_global.h"
/*********************
* DEFINES
*********************/
#ifdef FT_CONFIG_OPTION_ERROR_STRINGS
#define FT_ERROR_MSG(msg, error_code) \
LV_LOG_ERROR(msg " error(%d): %s", (int)error_code, FT_Error_String(error_code))
#else
#define FT_ERROR_MSG(msg, error_code) \
LV_LOG_ERROR(msg " error(%d)", (int)error_code)
#endif
#if LV_FREETYPE_CACHE_SIZE <= 0
#error "LV_FREETYPE_CACHE_SIZE must > 0"
#endif
#define ft_ctx LV_GLOBAL_DEFAULT()->ft_context
/**********************
* TYPEDEFS
**********************/
typedef struct _lv_freetype_font_dsc_t {
lv_font_t * font;
char * pathname;
uint16_t size;
uint16_t style;
} lv_freetype_font_dsc_t;
typedef struct _lv_freetype_context_t {
FT_Library library;
FTC_Manager cache_manager;
FTC_CMapCache cmap_cache;
FT_Face current_face;
#if LV_FREETYPE_SBIT_CACHE
FTC_SBitCache sbit_cache;
FTC_SBit sbit;
#else
FTC_ImageCache image_cache;
FT_Glyph image_glyph;
#endif
} lv_freetype_context_t;
/**********************
* STATIC PROTOTYPES
**********************/
static FT_Error freetpye_face_requester(FTC_FaceID face_id,
FT_Library library,
FT_Pointer req_data,
FT_Face * aface);
static FT_Error freetype_get_bold_glyph(const lv_font_t * font,
FT_Face face,
FT_UInt glyph_index,
lv_font_glyph_dsc_t * dsc_out);
static bool freetype_get_glyph_dsc_cb(const lv_font_t * font,
lv_font_glyph_dsc_t * dsc_out,
uint32_t unicode_letter,
uint32_t unicode_letter_next);
static const uint8_t * freetype_get_glyph_bitmap_cb(const lv_font_t * font,
uint32_t unicode_letter,
uint8_t * buf_out);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_result_t lv_freetype_init(uint16_t max_faces, uint16_t max_sizes, uint32_t max_bytes)
{
FT_Error error;
lv_freetype_context_t * context = ft_ctx = lv_malloc(sizeof(lv_freetype_context_t));
LV_ASSERT_MALLOC(context);
if(!context) {
LV_LOG_ERROR("malloc failed for lv_freetype_context_t");
return LV_RESULT_INVALID;
}
error = FT_Init_FreeType(&context->library);
if(error) {
FT_ERROR_MSG("FT_Init_FreeType", error);
return LV_RESULT_INVALID;
}
error = FTC_Manager_New(context->library,
max_faces,
max_sizes,
max_bytes,
freetpye_face_requester,
NULL,
&context->cache_manager);
if(error) {
FT_Done_FreeType(context->library);
FT_ERROR_MSG("FTC_Manager_New", error);
return LV_RESULT_INVALID;
}
error = FTC_CMapCache_New(context->cache_manager, &context->cmap_cache);
if(error) {
FT_ERROR_MSG("FTC_CMapCache_New", error);
goto failed;
}
#if LV_FREETYPE_SBIT_CACHE
error = FTC_SBitCache_New(context->cache_manager, &context->sbit_cache);
if(error) {
FT_ERROR_MSG("FTC_SBitCache_New", error);
goto failed;
}
#else
error = FTC_ImageCache_New(context->cache_manager, &context->image_cache);
if(error) {
FT_ERROR_MSG("FTC_ImageCache_New", error);
goto failed;
}
#endif
return LV_RESULT_OK;
failed:
FTC_Manager_Done(context->cache_manager);
FT_Done_FreeType(context->library);
return LV_RESULT_INVALID;
}
void lv_freetype_uninit(void)
{
lv_freetype_context_t * context = ft_ctx;
if(!context) {
return;
}
FTC_Manager_Done(context->cache_manager);
FT_Done_FreeType(context->library);
lv_free(context);
ft_ctx = NULL;
}
lv_font_t * lv_freetype_font_create(const char * pathname, uint16_t size, uint16_t style)
{
LV_ASSERT_NULL(pathname);
LV_ASSERT(size > 0);
size_t pathname_len = lv_strlen(pathname);
if(pathname_len == 0) {
LV_LOG_ERROR("pathname is empty");
return NULL;
}
size_t need_size = sizeof(lv_freetype_font_dsc_t) + sizeof(lv_font_t);
lv_freetype_font_dsc_t * dsc = lv_malloc(need_size);
LV_ASSERT_MALLOC(dsc);
if(!dsc) {
LV_LOG_ERROR("malloc failed for lv_freetype_font_dsc");
return NULL;
}
lv_memzero(dsc, need_size);
dsc->font = (lv_font_t *)(((uint8_t *)dsc) + sizeof(lv_freetype_font_dsc_t));
dsc->pathname = lv_malloc(pathname_len + 1);
LV_ASSERT_MALLOC(dsc->pathname);
if(!dsc->pathname) {
LV_LOG_ERROR("malloc failed for dsc->pathname");
lv_free(dsc);
return NULL;
}
lv_strcpy(dsc->pathname, pathname);
dsc->size = size;
dsc->style = style;
/* use to get font info */
FT_Size face_size;
struct FTC_ScalerRec_ scaler;
scaler.face_id = (FTC_FaceID)dsc;
scaler.width = size;
scaler.height = size;
scaler.pixel = 1;
FT_Error error = FTC_Manager_LookupSize(ft_ctx->cache_manager,
&scaler,
&face_size);
if(error) {
FT_ERROR_MSG("FTC_Manager_LookupSize", error);
lv_free(dsc->pathname);
lv_free(dsc);
return NULL;
}
lv_font_t * font = dsc->font;
font->dsc = dsc;
font->get_glyph_dsc = freetype_get_glyph_dsc_cb;
font->get_glyph_bitmap = freetype_get_glyph_bitmap_cb;
font->subpx = LV_FONT_SUBPX_NONE;
font->line_height = (face_size->face->size->metrics.height >> 6);
font->base_line = -(face_size->face->size->metrics.descender >> 6);
FT_Fixed scale = face_size->face->size->metrics.y_scale;
int8_t thickness = FT_MulFix(scale, face_size->face->underline_thickness) >> 6;
font->underline_position = FT_MulFix(scale, face_size->face->underline_position) >> 6;
font->underline_thickness = thickness < 1 ? 1 : thickness;
return font;
}
void lv_freetype_font_delete(lv_font_t * font)
{
LV_ASSERT_NULL(font);
lv_freetype_font_dsc_t * dsc = (lv_freetype_font_dsc_t *)(font->dsc);
LV_ASSERT_NULL(dsc);
FTC_Manager_RemoveFaceID(ft_ctx->cache_manager, (FTC_FaceID)dsc);
lv_free(dsc->pathname);
lv_free(dsc);
}
/**********************
* STATIC FUNCTIONS
**********************/
static FT_Error freetpye_face_requester(FTC_FaceID face_id,
FT_Library library,
FT_Pointer req_data,
FT_Face * aface)
{
LV_UNUSED(library);
LV_UNUSED(req_data);
lv_freetype_font_dsc_t * dsc = (lv_freetype_font_dsc_t *)face_id;
FT_Error error;
error = FT_New_Face(ft_ctx->library, dsc->pathname, 0, aface);
if(error) {
FT_ERROR_MSG("FT_New_Face", error);
}
return error;
}
static FT_Error freetype_get_bold_glyph(const lv_font_t * font,
FT_Face face,
FT_UInt glyph_index,
lv_font_glyph_dsc_t * dsc_out)
{
FT_Error error;
error = FT_Load_Glyph(face, glyph_index, FT_LOAD_DEFAULT);
if(error) {
FT_ERROR_MSG("FT_Load_Glyph", error);
return error;
}
lv_freetype_font_dsc_t * dsc = (lv_freetype_font_dsc_t *)(font->dsc);
if(face->glyph->format == FT_GLYPH_FORMAT_OUTLINE) {
if(dsc->style & LV_FREETYPE_FONT_STYLE_BOLD) {
int strength = 1 << 6;
error = FT_Outline_Embolden(&face->glyph->outline, strength);
if(error) {
FT_ERROR_MSG("FT_Outline_Embolden", error);
}
}
}
error = FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);
if(error) {
FT_ERROR_MSG("FT_Render_Glyph", error);
return error;
}
dsc_out->adv_w = (face->glyph->metrics.horiAdvance >> 6);
dsc_out->box_h = face->glyph->bitmap.rows; /*Height of the bitmap in [px]*/
dsc_out->box_w = face->glyph->bitmap.width; /*Width of the bitmap in [px]*/
dsc_out->ofs_x = face->glyph->bitmap_left; /*X offset of the bitmap in [pf]*/
dsc_out->ofs_y = face->glyph->bitmap_top -
face->glyph->bitmap.rows; /*Y offset of the bitmap measured from the as line*/
dsc_out->bpp = 8; /*Bit per pixel: 1/2/4/8*/
return FT_Err_Ok;
}
static bool freetype_get_glyph_dsc_cb(const lv_font_t * font,
lv_font_glyph_dsc_t * dsc_out,
uint32_t unicode_letter,
uint32_t unicode_letter_next)
{
LV_UNUSED(unicode_letter_next);
if(unicode_letter < 0x20) {
dsc_out->adv_w = 0;
dsc_out->box_h = 0;
dsc_out->box_w = 0;
dsc_out->ofs_x = 0;
dsc_out->ofs_y = 0;
dsc_out->bpp = 0;
return true;
}
lv_freetype_context_t * context = ft_ctx;
lv_freetype_font_dsc_t * dsc = (lv_freetype_font_dsc_t *)(font->dsc);
FTC_FaceID face_id = (FTC_FaceID)dsc;
FT_Size face_size;
FT_Error error;
struct FTC_ScalerRec_ scaler;
scaler.face_id = face_id;
scaler.width = dsc->size;
scaler.height = dsc->size;
scaler.pixel = 1;
error = FTC_Manager_LookupSize(context->cache_manager, &scaler, &face_size);
if(error) {
FT_ERROR_MSG("FTC_Manager_LookupSize", error);
return false;
}
FT_Face face = face_size->face;
FT_UInt charmap_index = FT_Get_Charmap_Index(face->charmap);
FT_UInt glyph_index = FTC_CMapCache_Lookup(context->cmap_cache, face_id, charmap_index, unicode_letter);
dsc_out->is_placeholder = glyph_index == 0;
if(dsc->style & LV_FREETYPE_FONT_STYLE_ITALIC) {
FT_Matrix italic_matrix;
italic_matrix.xx = 1 << 16;
italic_matrix.xy = 0x5800;
italic_matrix.yx = 0;
italic_matrix.yy = 1 << 16;
FT_Set_Transform(face, &italic_matrix, NULL);
}
if(dsc->style & LV_FREETYPE_FONT_STYLE_BOLD) {
context->current_face = face;
error = freetype_get_bold_glyph(font, face, glyph_index, dsc_out);
if(error) {
context->current_face = NULL;
return false;
}
goto end;
}
FTC_ImageTypeRec desc_type;
desc_type.face_id = face_id;
desc_type.flags = FT_LOAD_RENDER | FT_LOAD_TARGET_NORMAL;
desc_type.height = dsc->size;
desc_type.width = dsc->size;
#if LV_FREETYPE_SBIT_CACHE
error = FTC_SBitCache_Lookup(context->sbit_cache,
&desc_type,
glyph_index,
&context->sbit,
NULL);
if(error) {
FT_ERROR_MSG("FTC_SBitCache_Lookup", error);
return false;
}
FTC_SBit sbit = context->sbit;
dsc_out->adv_w = sbit->xadvance;
dsc_out->box_h = sbit->height; /*Height of the bitmap in [px]*/
dsc_out->box_w = sbit->width; /*Width of the bitmap in [px]*/
dsc_out->ofs_x = sbit->left; /*X offset of the bitmap in [pf]*/
dsc_out->ofs_y = sbit->top - sbit->height; /*Y offset of the bitmap measured from the as line*/
dsc_out->bpp = 8; /*Bit per pixel: 1/2/4/8*/
#else
error = FTC_ImageCache_Lookup(context->image_cache,
&desc_type,
glyph_index,
&context->image_glyph,
NULL);
if(error) {
FT_ERROR_MSG("ImageCache_Lookup", error);
return false;
}
if(context->image_glyph->format != FT_GLYPH_FORMAT_BITMAP) {
LV_LOG_ERROR("image_glyph->format != FT_GLYPH_FORMAT_BITMAP");
return false;
}
FT_BitmapGlyph glyph_bitmap = (FT_BitmapGlyph)context->image_glyph;
dsc_out->adv_w = (glyph_bitmap->root.advance.x >> 16);
dsc_out->box_h = glyph_bitmap->bitmap.rows; /*Height of the bitmap in [px]*/
dsc_out->box_w = glyph_bitmap->bitmap.width; /*Width of the bitmap in [px]*/
dsc_out->ofs_x = glyph_bitmap->left; /*X offset of the bitmap in [pf]*/
dsc_out->ofs_y = glyph_bitmap->top -
glyph_bitmap->bitmap.rows; /*Y offset of the bitmap measured from the as line*/
dsc_out->bpp = 8; /*Bit per pixel: 1/2/4/8*/
#endif
end:
if((dsc->style & LV_FREETYPE_FONT_STYLE_ITALIC) && (unicode_letter_next == '\0')) {
dsc_out->adv_w = dsc_out->box_w + dsc_out->ofs_x;
}
return true;
}
static const uint8_t * freetype_get_glyph_bitmap_cb(const lv_font_t * font, uint32_t unicode_letter, uint8_t * buf_out)
{
LV_UNUSED(unicode_letter);
LV_UNUSED(buf_out);
lv_freetype_font_dsc_t * dsc = (lv_freetype_font_dsc_t *)font->dsc;
lv_freetype_context_t * context = ft_ctx;
if(dsc->style & LV_FREETYPE_FONT_STYLE_BOLD) {
if(context->current_face && context->current_face->glyph->format == FT_GLYPH_FORMAT_BITMAP) {
return (const uint8_t *)(context->current_face->glyph->bitmap.buffer);
}
return NULL;
}
#if LV_FREETYPE_SBIT_CACHE
return (const uint8_t *)context->sbit->buffer;
#else
FT_BitmapGlyph glyph_bitmap = (FT_BitmapGlyph)context->image_glyph;
return (const uint8_t *)glyph_bitmap->bitmap.buffer;
#endif
}
#endif /*LV_USE_FREETYPE*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/freetype/lv_ftsystem.c | /**
* @file lv_ftsystem.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_FREETYPE && LV_FREETYPE_USE_LVGL_PORT
#include <ft2build.h>
#include FT_CONFIG_CONFIG_H
#include <freetype/internal/ftdebug.h>
#include <freetype/internal/ftstream.h>
#include <freetype/ftsystem.h>
#include <freetype/fterrors.h>
#include <freetype/fttypes.h>
/*********************
* DEFINES
*********************/
/* The macro FT_COMPONENT is used in trace mode. It is an implicit
* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log
* messages during execution.
*/
#undef FT_COMPONENT
#define FT_COMPONENT io
/* We use the macro STREAM_FILE for convenience to extract the */
/* system-specific stream handle from a given FreeType stream object */
#define STREAM_FILE( stream ) ( (lv_fs_file_t*)stream->descriptor.pointer )
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
FT_CALLBACK_DEF(unsigned long)
ft_lv_fs_stream_io(FT_Stream stream,
unsigned long offset,
unsigned char * buffer,
unsigned long count);
FT_CALLBACK_DEF(void)
ft_lv_fs_stream_close(FT_Stream stream);
FT_CALLBACK_DEF(void *)
ft_alloc(FT_Memory memory,
long size);
FT_CALLBACK_DEF(void *)
ft_realloc(FT_Memory memory,
long cur_size,
long new_size,
void * block);
FT_CALLBACK_DEF(void)
ft_free(FT_Memory memory,
void * block);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
#ifdef FT_DEBUG_MEMORY
extern FT_Int
ft_mem_debug_init(FT_Memory memory);
extern void
ft_mem_debug_done(FT_Memory memory);
#endif
/**********************
* GLOBAL FUNCTIONS
**********************/
#ifndef FT_CONFIG_OPTION_DISABLE_STREAM_SUPPORT
/* documentation is in ftstream.h */
FT_BASE_DEF(FT_Error)
FT_Stream_Open(FT_Stream stream,
const char * filepathname)
{
lv_fs_file_t file;
if(!stream)
return FT_THROW(Invalid_Stream_Handle);
stream->descriptor.pointer = NULL;
stream->pathname.pointer = (char *)filepathname;
stream->base = NULL;
stream->pos = 0;
stream->read = NULL;
stream->close = NULL;
lv_fs_res_t res = lv_fs_open(&file, filepathname, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) {
FT_ERROR(("FT_Stream_Open:"
" could not open `%s'\n", filepathname));
return FT_THROW(Cannot_Open_Resource);
}
lv_fs_seek(&file, 0, LV_FS_SEEK_END);
uint32_t pos;
res = lv_fs_tell(&file, &pos);
if(res != LV_FS_RES_OK) {
FT_ERROR(("FT_Stream_Open:"));
FT_ERROR((" opened `%s' but zero-sized\n", filepathname));
lv_fs_close(&file);
return FT_THROW(Cannot_Open_Stream);
}
stream->size = pos;
lv_fs_seek(&file, 0, LV_FS_SEEK_SET);
lv_fs_file_t * file_p = lv_malloc(sizeof(lv_fs_file_t));
LV_ASSERT_MALLOC(file_p);
if(!file_p) {
FT_ERROR(("FT_Stream_Open: malloc failed for file_p"));
lv_fs_close(&file);
return FT_THROW(Cannot_Open_Stream);
}
*file_p = file;
stream->descriptor.pointer = file_p;
stream->read = ft_lv_fs_stream_io;
stream->close = ft_lv_fs_stream_close;
FT_TRACE1(("FT_Stream_Open:"));
FT_TRACE1((" opened `%s' (%ld bytes) successfully\n",
filepathname, stream->size));
return FT_Err_Ok;
}
#endif /* !FT_CONFIG_OPTION_DISABLE_STREAM_SUPPORT */
/* documentation is in ftobjs.h */
FT_BASE_DEF(FT_Memory)
FT_New_Memory(void)
{
FT_Memory memory;
memory = (FT_Memory)lv_malloc(sizeof(*memory));
if(memory) {
memory->user = NULL;
memory->alloc = ft_alloc;
memory->realloc = ft_realloc;
memory->free = ft_free;
#ifdef FT_DEBUG_MEMORY
ft_mem_debug_init(memory);
#endif
}
return memory;
}
/* documentation is in ftobjs.h */
FT_BASE_DEF(void)
FT_Done_Memory(FT_Memory memory)
{
#ifdef FT_DEBUG_MEMORY
ft_mem_debug_done(memory);
#endif
lv_free(memory);
}
/**********************
* STATIC FUNCTIONS
**********************/
/**
* The memory allocation function.
* @param memory A pointer to the memory object.
* @param size The requested size in bytes.
* @return The address of newly allocated block.
*/
FT_CALLBACK_DEF(void *)
ft_alloc(FT_Memory memory,
long size)
{
FT_UNUSED(memory);
return lv_malloc((size_t)size);
}
/**
* The memory reallocation function.
* @param memory A pointer to the memory object.
* @param cur_size The current size of the allocated memory block.
* @param new_size The newly requested size in bytes.
* @param block The current address of the block in memory.
* @return The address of the reallocated memory block.
*/
FT_CALLBACK_DEF(void *)
ft_realloc(FT_Memory memory,
long cur_size,
long new_size,
void * block)
{
FT_UNUSED(memory);
FT_UNUSED(cur_size);
return lv_realloc(block, (size_t)new_size);
}
/**
* The memory release function.
* @param memory A pointer to the memory object.
* @param block The address of block in memory to be freed.
*/
FT_CALLBACK_DEF(void)
ft_free(FT_Memory memory,
void * block)
{
FT_UNUSED(memory);
lv_free(block);
}
#ifndef FT_CONFIG_OPTION_DISABLE_STREAM_SUPPORT
/**
* The function to close a stream.
* @param stream A pointer to the stream object.
*/
FT_CALLBACK_DEF(void)
ft_lv_fs_stream_close(FT_Stream stream)
{
lv_fs_file_t * file_p = STREAM_FILE(stream);
lv_fs_close(file_p);
lv_free(file_p);
stream->descriptor.pointer = NULL;
stream->size = 0;
stream->base = NULL;
}
/**
* The function to open a stream.
* @param stream A pointer to the stream object.
* @param offset The position in the data stream to start reading.
* @param buffer The address of buffer to store the read data.
* @param count The number of bytes to read from the stream.
* @return The number of bytes actually read. If `count' is zero (this is,
* the function is used for seeking), a non-zero return value
* indicates an error.
*/
FT_CALLBACK_DEF(unsigned long)
ft_lv_fs_stream_io(FT_Stream stream,
unsigned long offset,
unsigned char * buffer,
unsigned long count)
{
lv_fs_file_t * file_p;
if(!count && offset > stream->size)
return 1;
file_p = STREAM_FILE(stream);
if(stream->pos != offset)
lv_fs_seek(file_p, (long)offset, LV_FS_SEEK_SET);
if(count == 0)
return 0;
uint32_t br;
lv_fs_res_t res = lv_fs_read(file_p, buffer, count, &br);
return res == LV_FS_RES_OK ? br : 0;
}
#endif /* !FT_CONFIG_OPTION_DISABLE_STREAM_SUPPORT */
#endif/*LV_FREETYPE_USE_LV_FTSYSTEM*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/freetype/ftmodule.h | /*
* This file registers the FreeType modules compiled into the library.
*
* If you use GNU make, this file IS NOT USED! Instead, it is created in
* the objects directory (normally `<topdir>/objs/`) based on information
* from `<topdir>/modules.cfg`.
*
* Please read `docs/INSTALL.ANY` and `docs/CUSTOMIZE` how to compile
* FreeType without GNU make.
*
*/
/* FT_USE_MODULE( FT_Module_Class, autofit_module_class ) */
FT_USE_MODULE(FT_Driver_ClassRec, tt_driver_class)
/* FT_USE_MODULE( FT_Driver_ClassRec, t1_driver_class ) */
/* FT_USE_MODULE( FT_Driver_ClassRec, cff_driver_class ) */
/* FT_USE_MODULE( FT_Driver_ClassRec, t1cid_driver_class ) */
/* FT_USE_MODULE( FT_Driver_ClassRec, pfr_driver_class ) */
/* FT_USE_MODULE( FT_Driver_ClassRec, t42_driver_class ) */
/* FT_USE_MODULE( FT_Driver_ClassRec, winfnt_driver_class ) */
/* FT_USE_MODULE( FT_Driver_ClassRec, pcf_driver_class ) */
/* FT_USE_MODULE( FT_Driver_ClassRec, bdf_driver_class ) */
/* FT_USE_MODULE( FT_Module_Class, psaux_module_class ) */
/* FT_USE_MODULE( FT_Module_Class, psnames_module_class ) */
/* FT_USE_MODULE( FT_Module_Class, pshinter_module_class ) */
FT_USE_MODULE(FT_Module_Class, sfnt_module_class)
FT_USE_MODULE(FT_Renderer_Class, ft_smooth_renderer_class)
/* FT_USE_MODULE( FT_Renderer_Class, ft_raster1_renderer_class ) */
/* FT_USE_MODULE( FT_Renderer_Class, ft_sdf_renderer_class ) */
/* FT_USE_MODULE( FT_Renderer_Class, ft_bitmap_sdf_renderer_class ) */
/* FT_USE_MODULE( FT_Renderer_Class, ft_svg_renderer_class ) */
/* EOF */
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/libpng/lv_libpng.c | /**
* @file lv_libpng.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_LIBPNG
#include "lv_libpng.h"
#include <png.h>
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static lv_result_t decoder_info(lv_image_decoder_t * decoder, const void * src, lv_image_header_t * header);
static lv_result_t decoder_open(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc);
static void decoder_close(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc);
static const void * decode_png_file(const char * filename);
static lv_result_t try_cache(lv_image_decoder_dsc_t * dsc);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Register the PNG decoder functions in LVGL
*/
void lv_libpng_init(void)
{
lv_image_decoder_t * dec = lv_image_decoder_create();
lv_image_decoder_set_info_cb(dec, decoder_info);
lv_image_decoder_set_open_cb(dec, decoder_open);
lv_image_decoder_set_close_cb(dec, decoder_close);
}
void lv_libpng_deinit(void)
{
lv_image_decoder_t * dec = NULL;
while((dec = lv_image_decoder_get_next(dec)) != NULL) {
if(dec->info_cb == decoder_info) {
lv_image_decoder_delete(dec);
break;
}
}
}
/**********************
* STATIC FUNCTIONS
**********************/
/**
* Get info about a PNG image
* @param src can be file name or pointer to a C array
* @param header store the info here
* @return LV_RESULT_OK: no error; LV_RESULT_INVALID: can't get the info
*/
static lv_result_t decoder_info(lv_image_decoder_t * decoder, const void * src, lv_image_header_t * header)
{
LV_UNUSED(decoder); /*Unused*/
lv_image_src_t src_type = lv_image_src_get_type(src); /*Get the source type*/
/*If it's a PNG file...*/
if(src_type == LV_IMAGE_SRC_FILE) {
const char * fn = src;
lv_fs_file_t f;
lv_fs_res_t res = lv_fs_open(&f, fn, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) return LV_RESULT_INVALID;
/* Read the width and height from the file. They have a constant location:
* [16..19]: width
* [20..23]: height
*/
uint8_t buf[24];
uint32_t rn;
lv_fs_read(&f, buf, sizeof(buf), &rn);
lv_fs_close(&f);
if(rn != sizeof(buf)) return LV_RESULT_INVALID;
const uint8_t magic[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a};
if(memcmp(buf, magic, sizeof(magic)) != 0) return LV_RESULT_INVALID;
uint32_t * size = (uint32_t *)&buf[16];
/*Save the data in the header*/
header->always_zero = 0;
header->cf = LV_COLOR_FORMAT_ARGB8888;
/*The width and height are stored in Big endian format so convert them to little endian*/
header->w = (int32_t)((size[0] & 0xff000000) >> 24) + ((size[0] & 0x00ff0000) >> 8);
header->h = (int32_t)((size[1] & 0xff000000) >> 24) + ((size[1] & 0x00ff0000) >> 8);
return LV_RESULT_OK;
}
return LV_RESULT_INVALID; /*If didn't succeeded earlier then it's an error*/
}
/**
* Open a PNG image and return the decided image
* @param src can be file name or pointer to a C array
* @param style style of the image object (unused now but certain formats might use it)
* @return pointer to the decoded image or `LV_IMAGE_DECODER_OPEN_FAIL` if failed
*/
static lv_result_t decoder_open(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder); /*Unused*/
/*Check the cache first*/
if(try_cache(dsc) == LV_RESULT_OK) return LV_RESULT_OK;
/*If it's a PNG file...*/
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
const char * fn = dsc->src;
lv_cache_lock();
lv_cache_entry_t * cache = lv_cache_add(dsc->header.w * dsc->header.h * sizeof(uint32_t));
if(cache == NULL) {
lv_cache_unlock();
return LV_RESULT_INVALID;
}
uint32_t t = lv_tick_get();
const void * decoded_img = decode_png_file(fn);
t = lv_tick_elaps(t);
cache->weight = t;
cache->data = decoded_img;
cache->free_data = 1;
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
cache->src = lv_strdup(dsc->src);
cache->src_type = LV_CACHE_SRC_TYPE_STR;
cache->free_src = 1;
}
else {
cache->src_type = LV_CACHE_SRC_TYPE_PTR;
cache->src = dsc->src;
}
dsc->img_data = lv_cache_get_data(cache);
dsc->cache_entry = cache;
lv_cache_unlock();
return LV_RESULT_OK; /*The image is fully decoded. Return with its pointer*/
}
return LV_RESULT_INVALID; /*If not returned earlier then it failed*/
}
/**
* Free the allocated resources
*/
static void decoder_close(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder); /*Unused*/
lv_cache_lock();
lv_cache_release(dsc->cache_entry);
lv_cache_unlock();
}
static lv_result_t try_cache(lv_image_decoder_dsc_t * dsc)
{
lv_cache_lock();
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
const char * fn = dsc->src;
lv_cache_entry_t * cache = lv_cache_find(fn, LV_CACHE_SRC_TYPE_STR, 0, 0);
if(cache) {
dsc->img_data = lv_cache_get_data(cache);
dsc->cache_entry = cache; /*Save the cache to release it in decoder_close*/
lv_cache_unlock();
return LV_RESULT_OK;
}
}
lv_cache_unlock();
return LV_RESULT_INVALID;
}
static uint8_t * alloc_file(const char * filename, uint32_t * size)
{
uint8_t * data = NULL;
lv_fs_file_t f;
uint32_t data_size;
uint32_t rn;
lv_fs_res_t res;
*size = 0;
res = lv_fs_open(&f, filename, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) {
LV_LOG_WARN("can't open %s", filename);
return NULL;
}
res = lv_fs_seek(&f, 0, LV_FS_SEEK_END);
if(res != LV_FS_RES_OK) {
goto failed;
}
res = lv_fs_tell(&f, &data_size);
if(res != LV_FS_RES_OK) {
goto failed;
}
res = lv_fs_seek(&f, 0, LV_FS_SEEK_SET);
if(res != LV_FS_RES_OK) {
goto failed;
}
/*Read file to buffer*/
data = lv_malloc(data_size);
if(data == NULL) {
LV_LOG_WARN("malloc failed for data");
goto failed;
}
res = lv_fs_read(&f, data, data_size, &rn);
if(res == LV_FS_RES_OK && rn == data_size) {
*size = rn;
}
else {
LV_LOG_WARN("read file failed");
lv_free(data);
data = NULL;
}
failed:
lv_fs_close(&f);
return data;
}
static const void * decode_png_file(const char * filename)
{
int ret;
/*Prepare png_image*/
png_image image;
lv_memzero(&image, sizeof(image));
image.version = PNG_IMAGE_VERSION;
uint32_t data_size;
uint8_t * data = alloc_file(filename, &data_size);
if(data == NULL) {
LV_LOG_WARN("can't load file: %s", filename);
return NULL;
}
/*Ready to read file*/
ret = png_image_begin_read_from_memory(&image, data, data_size);
if(!ret) {
LV_LOG_ERROR("png file: %s read failed: %d", filename, ret);
lv_free(data);
return NULL;
}
/*Set color format*/
image.format = PNG_FORMAT_BGRA;
/*Alloc image buffer*/
size_t image_size = PNG_IMAGE_SIZE(image);
void * image_data = lv_draw_buf_malloc(image_size, LV_COLOR_FORMAT_ARGB8888);
if(image_data) {
/*Start decoding*/
ret = png_image_finish_read(&image, NULL, image_data, 0, NULL);
if(!ret) {
LV_LOG_ERROR("png decode failed: %d", ret);
lv_draw_buf_free(image_data);
image_data = NULL;
}
}
else {
LV_LOG_ERROR("png alloc %zu failed", image_size);
}
/*free decoder*/
png_image_free(&image);
lv_free(data);
return image_data;
}
#endif /*LV_USE_LIBPNG*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/libpng/lv_libpng.h | /**
* @file lv_libpng.h
*
*/
#ifndef LV_LIBPNG_H
#define LV_LIBPNG_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../lv_conf_internal.h"
#if LV_USE_LIBPNG
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Register the PNG decoder functions in LVGL
*/
void lv_libpng_init(void);
void lv_libpng_deinit(void);
/**********************
* MACROS
**********************/
#endif /*LV_USE_LIBPNG*/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*LV_LIBPNG_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/bmp/lv_bmp.h | /**
* @file lv_bmp.h
*
*/
#ifndef LV_BMP_H
#define LV_BMP_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../lv_conf_internal.h"
#if LV_USE_BMP
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
void lv_bmp_init(void);
/**********************
* MACROS
**********************/
#endif /*LV_USE_BMP*/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*LV_BMP_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/bmp/lv_bmp.c | /**
* @file lv_bmp.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_BMP
#include <string.h>
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_fs_file_t f;
unsigned int px_offset;
int px_width;
int px_height;
unsigned int bpp;
int row_size_bytes;
} bmp_dsc_t;
/**********************
* STATIC PROTOTYPES
**********************/
static lv_result_t decoder_info(lv_image_decoder_t * decoder, const void * src, lv_image_header_t * header);
static lv_result_t decoder_open(lv_image_decoder_t * dec, lv_image_decoder_dsc_t * dsc);
static lv_result_t decoder_get_area(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc,
const lv_area_t * full_area, lv_area_t * decoded_area);
static void decoder_close(lv_image_decoder_t * dec, lv_image_decoder_dsc_t * dsc);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_bmp_init(void)
{
lv_image_decoder_t * dec = lv_image_decoder_create();
lv_image_decoder_set_info_cb(dec, decoder_info);
lv_image_decoder_set_open_cb(dec, decoder_open);
lv_image_decoder_set_get_area_cb(dec, decoder_get_area);
lv_image_decoder_set_close_cb(dec, decoder_close);
}
/**********************
* STATIC FUNCTIONS
**********************/
/**
* Get info about a PNG image
* @param src can be file name or pointer to a C array
* @param header store the info here
* @return LV_RESULT_OK: no error; LV_RESULT_INVALID: can't get the info
*/
static lv_result_t decoder_info(lv_image_decoder_t * decoder, const void * src, lv_image_header_t * header)
{
LV_UNUSED(decoder);
lv_image_src_t src_type = lv_image_src_get_type(src); /*Get the source type*/
/*If it's a BMP file...*/
if(src_type == LV_IMAGE_SRC_FILE) {
const char * fn = src;
if(strcmp(lv_fs_get_ext(fn), "bmp") == 0) { /*Check the extension*/
/*Save the data in the header*/
lv_fs_file_t f;
lv_fs_res_t res = lv_fs_open(&f, src, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) return LV_RESULT_INVALID;
uint8_t headers[54];
lv_fs_read(&f, headers, 54, NULL);
uint32_t w;
uint32_t h;
memcpy(&w, headers + 18, 4);
memcpy(&h, headers + 22, 4);
header->w = w;
header->h = h;
header->always_zero = 0;
lv_fs_close(&f);
uint16_t bpp;
memcpy(&bpp, headers + 28, 2);
switch(bpp) {
case 16:
header->cf = LV_COLOR_FORMAT_RGB565;
break;
case 24:
header->cf = LV_COLOR_FORMAT_RGB888;
break;
case 32:
header->cf = LV_COLOR_FORMAT_ARGB8888;
break;
default:
LV_LOG_WARN("Not supported bpp: %d", bpp);
return LV_RESULT_OK;
}
return LV_RESULT_OK;
}
}
/* BMP file as data not supported for simplicity.
* Convert them to LVGL compatible C arrays directly. */
else if(src_type == LV_IMAGE_SRC_VARIABLE) {
return LV_RESULT_INVALID;
}
return LV_RESULT_INVALID; /*If didn't succeeded earlier then it's an error*/
}
/**
* Open a PNG image and return the decided image
* @param src can be file name or pointer to a C array
* @param style style of the image object (unused now but certain formats might use it)
* @return pointer to the decoded image or `LV_IMAGE_DECODER_OPEN_FAIL` if failed
*/
static lv_result_t decoder_open(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder);
/*If it's a PNG file...*/
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
const char * fn = dsc->src;
if(strcmp(lv_fs_get_ext(fn), "bmp") != 0) {
return LV_RESULT_INVALID; /*Check the extension*/
}
bmp_dsc_t b;
memset(&b, 0x00, sizeof(b));
lv_fs_res_t res = lv_fs_open(&b.f, dsc->src, LV_FS_MODE_RD);
if(res == LV_RESULT_OK) return LV_RESULT_INVALID;
uint8_t header[54];
lv_fs_read(&b.f, header, 54, NULL);
if(0x42 != header[0] || 0x4d != header[1]) {
lv_fs_close(&b.f);
return LV_RESULT_INVALID;
}
memcpy(&b.px_offset, header + 10, 4);
memcpy(&b.px_width, header + 18, 4);
memcpy(&b.px_height, header + 22, 4);
memcpy(&b.bpp, header + 28, 2);
b.row_size_bytes = ((b.bpp * b.px_width + 31) / 32) * 4;
dsc->user_data = lv_malloc(sizeof(bmp_dsc_t));
LV_ASSERT_MALLOC(dsc->user_data);
if(dsc->user_data == NULL) return LV_RESULT_INVALID;
memcpy(dsc->user_data, &b, sizeof(b));
dsc->img_data = NULL;
return LV_RESULT_OK;
}
/* BMP file as data not supported for simplicity.
* Convert them to LVGL compatible C arrays directly. */
else if(dsc->src_type == LV_IMAGE_SRC_VARIABLE) {
return LV_RESULT_INVALID;
}
return LV_RESULT_INVALID; /*If not returned earlier then it failed*/
}
static lv_result_t decoder_get_area(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc,
const lv_area_t * full_area, lv_area_t * decoded_area)
{
LV_UNUSED(decoder);
bmp_dsc_t * b = dsc->user_data;
uint32_t line_width_byte = lv_area_get_width(full_area) * (b->bpp / 8);
if(decoded_area->y1 == LV_COORD_MIN) {
*decoded_area = *full_area;
decoded_area->y2 = decoded_area->y1;
dsc->img_data = lv_malloc(line_width_byte);
}
else {
decoded_area->y1++;
decoded_area->y2++;
}
if(decoded_area->y1 > full_area->y2) {
return LV_RESULT_INVALID;
}
else {
int32_t y = (b->px_height - 1) - (decoded_area->y1); /*BMP images are stored upside down*/
uint32_t p = b->px_offset + b->row_size_bytes * y;
p += (decoded_area->x1) * (b->bpp / 8);
lv_fs_seek(&b->f, p, LV_FS_SEEK_SET);
lv_fs_read(&b->f, (void *)dsc->img_data, line_width_byte, NULL);
return LV_RESULT_OK;
}
}
/**
* Free the allocated resources
*/
static void decoder_close(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder);
bmp_dsc_t * b = dsc->user_data;
lv_fs_close(&b->f);
lv_free(dsc->user_data);
if(dsc->img_data) lv_free((void *)dsc->img_data);
}
#endif /*LV_USE_BMP*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/lodepng/lv_lodepng.c | /**
* @file lv_lodepng.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_LODEPNG
#include "lv_lodepng.h"
#include "lodepng.h"
#include <stdlib.h>
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static lv_result_t decoder_info(struct _lv_image_decoder_t * decoder, const void * src, lv_image_header_t * header);
static lv_result_t decoder_open(lv_image_decoder_t * dec, lv_image_decoder_dsc_t * dsc);
static void decoder_close(lv_image_decoder_t * dec, lv_image_decoder_dsc_t * dsc);
static void convert_color_depth(uint8_t * img_p, uint32_t px_cnt);
static const void * decode_png_data(const void * png_data, size_t png_data_size);
static lv_result_t try_cache(lv_image_decoder_dsc_t * dsc);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Register the PNG decoder functions in LVGL
*/
void lv_lodepng_init(void)
{
lv_image_decoder_t * dec = lv_image_decoder_create();
lv_image_decoder_set_info_cb(dec, decoder_info);
lv_image_decoder_set_open_cb(dec, decoder_open);
lv_image_decoder_set_close_cb(dec, decoder_close);
}
void lv_lodepng_deinit(void)
{
lv_image_decoder_t * dec = NULL;
while((dec = lv_image_decoder_get_next(dec)) != NULL) {
if(dec->info_cb == decoder_info) {
lv_image_decoder_delete(dec);
break;
}
}
}
/**********************
* STATIC FUNCTIONS
**********************/
/**
* Get info about a PNG image
* @param decoder pointer to the decoder where this function belongs
* @param src can be file name or pointer to a C array
* @param header image information is set in header parameter
* @return LV_RESULT_OK: no error; LV_RESULT_INVALID: can't get the info
*/
static lv_result_t decoder_info(struct _lv_image_decoder_t * decoder, const void * src, lv_image_header_t * header)
{
(void) decoder; /*Unused*/
lv_image_src_t src_type = lv_image_src_get_type(src); /*Get the source type*/
/*If it's a PNG file...*/
if(src_type == LV_IMAGE_SRC_FILE) {
const char * fn = src;
if(strcmp(lv_fs_get_ext(fn), "png") == 0) { /*Check the extension*/
/* Read the width and height from the file. They have a constant location:
* [16..23]: width
* [24..27]: height
*/
uint32_t size[2];
lv_fs_file_t f;
lv_fs_res_t res = lv_fs_open(&f, fn, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) return LV_RESULT_INVALID;
lv_fs_seek(&f, 16, LV_FS_SEEK_SET);
uint32_t rn;
lv_fs_read(&f, &size, 8, &rn);
lv_fs_close(&f);
if(rn != 8) return LV_RESULT_INVALID;
/*Save the data in the header*/
header->always_zero = 0;
header->cf = LV_COLOR_FORMAT_ARGB8888;
/*The width and height are stored in Big endian format so convert them to little endian*/
header->w = (int32_t)((size[0] & 0xff000000) >> 24) + ((size[0] & 0x00ff0000) >> 8);
header->h = (int32_t)((size[1] & 0xff000000) >> 24) + ((size[1] & 0x00ff0000) >> 8);
return LV_RESULT_OK;
}
}
/*If it's a PNG file in a C array...*/
else if(src_type == LV_IMAGE_SRC_VARIABLE) {
const lv_image_dsc_t * img_dsc = src;
const uint32_t data_size = img_dsc->data_size;
const uint32_t * size = ((uint32_t *)img_dsc->data) + 4;
const uint8_t magic[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a};
if(data_size < sizeof(magic)) return LV_RESULT_INVALID;
if(memcmp(magic, img_dsc->data, sizeof(magic))) return LV_RESULT_INVALID;
header->always_zero = 0;
header->cf = LV_COLOR_FORMAT_ARGB8888;
if(img_dsc->header.w) {
header->w = img_dsc->header.w; /*Save the image width*/
}
else {
header->w = (int32_t)((size[0] & 0xff000000) >> 24) + ((size[0] & 0x00ff0000) >> 8);
}
if(img_dsc->header.h) {
header->h = img_dsc->header.h; /*Save the color height*/
}
else {
header->h = (int32_t)((size[1] & 0xff000000) >> 24) + ((size[1] & 0x00ff0000) >> 8);
}
return LV_RESULT_OK;
}
return LV_RESULT_INVALID; /*If didn't succeeded earlier then it's an error*/
}
/**
* Open a PNG image and decode it into dsc.img_data
* @param decoder pointer to the decoder where this function belongs
* @param dsc decoded image descriptor
* @return LV_RESULT_OK: no error; LV_RESULT_INVALID: can't open the image
*/
static lv_result_t decoder_open(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
(void) decoder; /*Unused*/
/*Check the cache first*/
if(try_cache(dsc) == LV_RESULT_OK) return LV_RESULT_OK;
const uint8_t * png_data = NULL;
size_t png_data_size = 0;
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
const char * fn = dsc->src;
if(strcmp(lv_fs_get_ext(fn), "png") == 0) { /*Check the extension*/
unsigned error;
error = lodepng_load_file((void *)&png_data, &png_data_size, fn); /*Load the file*/
if(error) {
if(png_data != NULL) {
lv_free((void *)png_data);
}
LV_LOG_WARN("error %u: %s\n", error, lodepng_error_text(error));
return LV_RESULT_INVALID;
}
}
}
else if(dsc->src_type == LV_IMAGE_SRC_VARIABLE) {
const lv_image_dsc_t * img_dsc = dsc->src;
png_data = img_dsc->data;
png_data_size = img_dsc->data_size;
}
else {
return LV_RESULT_INVALID;
}
lv_cache_lock();
lv_cache_entry_t * cache = lv_cache_add(dsc->header.w * dsc->header.h * 4);
if(cache == NULL) {
lv_cache_unlock();
return LV_RESULT_INVALID;
}
uint32_t t = lv_tick_get();
const void * decoded_img = decode_png_data(png_data, png_data_size);
t = lv_tick_elaps(t);
cache->weight = t;
cache->data = decoded_img;
cache->free_data = 1;
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
cache->src = lv_strdup(dsc->src);
cache->src_type = LV_CACHE_SRC_TYPE_STR;
cache->free_src = 1;
lv_free((void *)png_data);
}
else {
cache->src_type = LV_CACHE_SRC_TYPE_PTR;
cache->src = dsc->src;
}
dsc->img_data = lv_cache_get_data(cache);
dsc->cache_entry = cache;
lv_cache_unlock();
return LV_RESULT_OK; /*If not returned earlier then it failed*/
}
/**
* Close PNG image and free data
* @param decoder pointer to the decoder where this function belongs
* @param dsc decoded image descriptor
* @return LV_RESULT_OK: no error; LV_RESULT_INVALID: can't open the image
*/
static void decoder_close(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder);
lv_cache_lock();
lv_cache_release(dsc->cache_entry);
lv_cache_unlock();
}
static lv_result_t try_cache(lv_image_decoder_dsc_t * dsc)
{
lv_cache_lock();
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
const char * fn = dsc->src;
lv_cache_entry_t * cache = lv_cache_find(fn, LV_CACHE_SRC_TYPE_STR, 0, 0);
if(cache) {
dsc->img_data = lv_cache_get_data(cache);
dsc->cache_entry = cache; /*Save the cache to release it in decoder_close*/
lv_cache_unlock();
return LV_RESULT_OK;
}
}
else if(dsc->src_type == LV_IMAGE_SRC_VARIABLE) {
const lv_image_dsc_t * img_dsc = dsc->src;
lv_cache_entry_t * cache = lv_cache_find(img_dsc, LV_CACHE_SRC_TYPE_PTR, 0, 0);
if(cache) {
dsc->img_data = lv_cache_get_data(cache);
dsc->cache_entry = cache; /*Save the cache to release it in decoder_close*/
lv_cache_unlock();
return LV_RESULT_OK;
}
}
lv_cache_unlock();
return LV_RESULT_INVALID;
}
static const void * decode_png_data(const void * png_data, size_t png_data_size)
{
unsigned png_width; /*Not used, just required by the decoder*/
unsigned png_height; /*Not used, just required by the decoder*/
uint8_t * img_data = NULL;
/*Decode the image in ARGB8888 */
unsigned error = lodepng_decode32(&img_data, &png_width, &png_height, png_data, png_data_size);
if(error) {
if(img_data != NULL) lv_free(img_data);
return NULL;
}
/*Convert the image to the system's color depth*/
convert_color_depth(img_data, png_width * png_height);
return img_data;
}
/**
* If the display is not in 32 bit format (ARGB888) then convert the image to the current color depth
* @param img the ARGB888 image
* @param px_cnt number of pixels in `img`
*/
static void convert_color_depth(uint8_t * img_p, uint32_t px_cnt)
{
lv_color32_t * img_argb = (lv_color32_t *)img_p;
uint32_t i;
for(i = 0; i < px_cnt; i++) {
uint8_t blue = img_argb[i].blue;
img_argb[i].blue = img_argb[i].red;
img_argb[i].red = blue;
}
}
#endif /*LV_USE_LODEPNG*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/lodepng/lodepng.h | /*
LodePNG version 20201017
Copyright (c) 2005-2020 Lode Vandevenne
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef LODEPNG_H
#define LODEPNG_H
#include <string.h> /*for size_t*/
#include "../../../lvgl.h"
#if LV_USE_LODEPNG
extern const char * LODEPNG_VERSION_STRING;
/*
The following #defines are used to create code sections. They can be disabled
to disable code sections, which can give faster compile time and smaller binary.
The "NO_COMPILE" defines are designed to be used to pass as defines to the
compiler command to disable them without modifying this header, e.g.
-DLODEPNG_NO_COMPILE_ZLIB for gcc.
In addition to those below, you can also define LODEPNG_NO_COMPILE_CRC to
allow implementing a custom lodepng_crc32.
*/
/*deflate & zlib. If disabled, you must specify alternative zlib functions in
the custom_zlib field of the compress and decompress settings*/
#ifndef LODEPNG_NO_COMPILE_ZLIB
#define LODEPNG_COMPILE_ZLIB
#endif
/*png encoder and png decoder*/
#ifndef LODEPNG_NO_COMPILE_PNG
#define LODEPNG_COMPILE_PNG
#endif
/*deflate&zlib decoder and png decoder*/
#ifndef LODEPNG_NO_COMPILE_DECODER
#define LODEPNG_COMPILE_DECODER
#endif
/*deflate&zlib encoder and png encoder*/
#ifndef LODEPNG_NO_COMPILE_ENCODER
#define LODEPNG_COMPILE_ENCODER
#endif
/*the optional built in harddisk file loading and saving functions*/
#ifndef LODEPNG_NO_COMPILE_DISK
#define LODEPNG_COMPILE_DISK
#endif
/*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/
#ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS
#define LODEPNG_COMPILE_ANCILLARY_CHUNKS
#endif
/*ability to convert error numerical codes to English text string*/
#ifndef LODEPNG_NO_COMPILE_ERROR_TEXT
#define LODEPNG_COMPILE_ERROR_TEXT
#endif
/*Compile the default allocators (C's free, malloc and realloc). If you disable this,
you can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your
source files with custom allocators.*/
#ifndef LODEPNG_NO_COMPILE_ALLOCATORS
#define LODEPNG_COMPILE_ALLOCATORS
#endif
/*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/
#ifdef __cplusplus
#ifndef LODEPNG_NO_COMPILE_CPP
#define LODEPNG_COMPILE_CPP
#endif
#endif
#ifdef LODEPNG_COMPILE_CPP
#include <vector>
#include <string>
#endif /*LODEPNG_COMPILE_CPP*/
#ifdef LODEPNG_COMPILE_PNG
/*The PNG color types (also used for raw image).*/
typedef enum _LodePNGColorType {
LCT_GREY = 0, /*grayscale: 1,2,4,8,16 bit*/
LCT_RGB = 2, /*RGB: 8,16 bit*/
LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/
LCT_GREY_ALPHA = 4, /*grayscale with alpha: 8,16 bit*/
LCT_RGBA = 6, /*RGB with alpha: 8,16 bit*/
/*LCT_MAX_OCTET_VALUE lets the compiler allow this enum to represent any invalid
byte value from 0 to 255 that could be present in an invalid PNG file header. Do
not use, compare with or set the name LCT_MAX_OCTET_VALUE, instead either use
the valid color type names above, or numeric values like 1 or 7 when checking for
particular disallowed color type byte values, or cast to integer to print it.*/
LCT_MAX_OCTET_VALUE = 255
} LodePNGColorType;
#ifdef LODEPNG_COMPILE_DECODER
/*
Converts PNG data in memory to raw pixel data.
out: Output parameter. Pointer to buffer that will contain the raw pixel data.
After decoding, its size is w * h * (bytes per pixel) bytes larger than
initially. Bytes per pixel depends on colortype and bitdepth.
Must be freed after usage with free(*out).
Note: for 16-bit per channel colors, uses big endian format like PNG does.
w: Output parameter. Pointer to width of pixel data.
h: Output parameter. Pointer to height of pixel data.
in: Memory buffer with the PNG file.
insize: size of the in buffer.
colortype: the desired color type for the raw output image. See explanation on PNG color types.
bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types.
Return value: LodePNG error code (0 means no error).
*/
unsigned lodepng_decode_memory(unsigned char ** out, unsigned * w, unsigned * h,
const unsigned char * in, size_t insize,
LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/
unsigned lodepng_decode32(unsigned char ** out, unsigned * w, unsigned * h,
const unsigned char * in, size_t insize);
/*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/
unsigned lodepng_decode24(unsigned char ** out, unsigned * w, unsigned * h,
const unsigned char * in, size_t insize);
#ifdef LODEPNG_COMPILE_DISK
/*
Load PNG from disk, from file with given name.
Same as the other decode functions, but instead takes a filename as input.
*/
unsigned lodepng_decode_file(unsigned char ** out, unsigned * w, unsigned * h,
const char * filename,
LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/
unsigned lodepng_decode32_file(unsigned char ** out, unsigned * w, unsigned * h,
const char * filename);
/*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/
unsigned lodepng_decode24_file(unsigned char ** out, unsigned * w, unsigned * h,
const char * filename);
#endif /*LODEPNG_COMPILE_DISK*/
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/*
Converts raw pixel data into a PNG image in memory. The colortype and bitdepth
of the output PNG image cannot be chosen, they are automatically determined
by the colortype, bitdepth and content of the input pixel data.
Note: for 16-bit per channel colors, needs big endian format like PNG does.
out: Output parameter. Pointer to buffer that will contain the PNG image data.
Must be freed after usage with free(*out).
outsize: Output parameter. Pointer to the size in bytes of the out buffer.
image: The raw pixel data to encode. The size of this buffer should be
w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth.
w: width of the raw pixel data in pixels.
h: height of the raw pixel data in pixels.
colortype: the color type of the raw input image. See explanation on PNG color types.
bitdepth: the bit depth of the raw input image. See explanation on PNG color types.
Return value: LodePNG error code (0 means no error).
*/
unsigned lodepng_encode_memory(unsigned char ** out, size_t * outsize,
const unsigned char * image, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/
unsigned lodepng_encode32(unsigned char ** out, size_t * outsize,
const unsigned char * image, unsigned w, unsigned h);
/*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/
unsigned lodepng_encode24(unsigned char ** out, size_t * outsize,
const unsigned char * image, unsigned w, unsigned h);
#ifdef LODEPNG_COMPILE_DISK
/*
Converts raw pixel data into a PNG file on disk.
Same as the other encode functions, but instead takes a filename as output.
NOTE: This overwrites existing files without warning!
*/
unsigned lodepng_encode_file(const char * filename,
const unsigned char * image, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/
unsigned lodepng_encode32_file(const char * filename,
const unsigned char * image, unsigned w, unsigned h);
/*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/
unsigned lodepng_encode24_file(const char * filename,
const unsigned char * image, unsigned w, unsigned h);
#endif /*LODEPNG_COMPILE_DISK*/
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_CPP
namespace lodepng
{
#ifdef LODEPNG_COMPILE_DECODER
/*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype
is the format to output the pixels to. Default is RGBA 8-bit per channel.*/
unsigned decode(std::vector<unsigned char> & out, unsigned & w, unsigned & h,
const unsigned char * in, size_t insize,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
unsigned decode(std::vector<unsigned char> & out, unsigned & w, unsigned & h,
const std::vector<unsigned char> & in,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#ifdef LODEPNG_COMPILE_DISK
/*
Converts PNG file from disk to raw pixel data in memory.
Same as the other decode functions, but instead takes a filename as input.
*/
unsigned decode(std::vector<unsigned char> & out, unsigned & w, unsigned & h,
const std::string & filename,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_DECODER */
#ifdef LODEPNG_COMPILE_ENCODER
/*Same as lodepng_encode_memory, but encodes to an std::vector. colortype
is that of the raw input data. The output PNG color type will be auto chosen.*/
unsigned encode(std::vector<unsigned char> & out,
const unsigned char * in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
unsigned encode(std::vector<unsigned char> & out,
const std::vector<unsigned char> & in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#ifdef LODEPNG_COMPILE_DISK
/*
Converts 32-bit RGBA raw pixel data into a PNG file on disk.
Same as the other encode functions, but instead takes a filename as output.
NOTE: This overwrites existing files without warning!
*/
unsigned encode(const std::string & filename,
const unsigned char * in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
unsigned encode(const std::string & filename,
const std::vector<unsigned char> & in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_ENCODER */
} /* namespace lodepng */
#endif /*LODEPNG_COMPILE_CPP*/
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ERROR_TEXT
/*Returns an English description of the numerical error code.*/
const char * lodepng_error_text(unsigned code);
#endif /*LODEPNG_COMPILE_ERROR_TEXT*/
#ifdef LODEPNG_COMPILE_DECODER
/*Settings for zlib decompression*/
typedef struct _LodePNGDecompressSettings LodePNGDecompressSettings;
struct _LodePNGDecompressSettings {
/* Check LodePNGDecoderSettings for more ignorable errors such as ignore_crc */
unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/
unsigned ignore_nlen; /*ignore complement of len checksum in uncompressed blocks*/
/*Maximum decompressed size, beyond this the decoder may (and is encouraged to) stop decoding,
return an error, output a data size > max_output_size and all the data up to that point. This is
not hard limit nor a guarantee, but can prevent excessive memory usage. This setting is
ignored by the PNG decoder, but is used by the deflate/zlib decoder and can be used by custom ones.
Set to 0 to impose no limit (the default).*/
size_t max_output_size;
/*use custom zlib decoder instead of built in one (default: null).
Should return 0 if success, any non-0 if error (numeric value not exposed).*/
unsigned(*custom_zlib)(unsigned char **, size_t *,
const unsigned char *, size_t,
const LodePNGDecompressSettings *);
/*use custom deflate decoder instead of built in one (default: null)
if custom_zlib is not null, custom_inflate is ignored (the zlib format uses deflate).
Should return 0 if success, any non-0 if error (numeric value not exposed).*/
unsigned(*custom_inflate)(unsigned char **, size_t *,
const unsigned char *, size_t,
const LodePNGDecompressSettings *);
const void * custom_context; /*optional custom settings for custom functions*/
};
extern const LodePNGDecompressSettings lodepng_default_decompress_settings;
void lodepng_decompress_settings_init(LodePNGDecompressSettings * settings);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/*
Settings for zlib compression. Tweaking these settings tweaks the balance
between speed and compression ratio.
*/
typedef struct _LodePNGCompressSettings LodePNGCompressSettings;
struct _LodePNGCompressSettings { /*deflate = compress*/
/*LZ77 related settings*/
unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/
unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/
unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/
unsigned minmatch; /*minimum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/
unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/
unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/
/*use custom zlib encoder instead of built in one (default: null)*/
unsigned(*custom_zlib)(unsigned char **, size_t *,
const unsigned char *, size_t,
const LodePNGCompressSettings *);
/*use custom deflate encoder instead of built in one (default: null)
if custom_zlib is used, custom_deflate is ignored since only the built in
zlib function will call custom_deflate*/
unsigned(*custom_deflate)(unsigned char **, size_t *,
const unsigned char *, size_t,
const LodePNGCompressSettings *);
const void * custom_context; /*optional custom settings for custom functions*/
};
extern const LodePNGCompressSettings lodepng_default_compress_settings;
void lodepng_compress_settings_init(LodePNGCompressSettings * settings);
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_PNG
/*
Color mode of an image. Contains all information required to decode the pixel
bits to RGBA colors. This information is the same as used in the PNG file
format, and is used both for PNG and raw image data in LodePNG.
*/
typedef struct _LodePNGColorMode {
/*header (IHDR)*/
LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/
unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/
/*
palette (PLTE and tRNS)
Dynamically allocated with the colors of the palette, including alpha.
This field may not be allocated directly, use lodepng_color_mode_init first,
then lodepng_palette_add per color to correctly initialize it (to ensure size
of exactly 1024 bytes).
The alpha channels must be set as well, set them to 255 for opaque images.
When decoding, by default you can ignore this palette, since LodePNG already
fills the palette colors in the pixels of the raw RGBA output.
The palette is only supported for color type 3.
*/
unsigned char * palette; /*palette in RGBARGBA... order. Must be either 0, or when allocated must have 1024 bytes*/
size_t palettesize; /*palette size in number of colors (amount of used bytes is 4 * palettesize)*/
/*
transparent color key (tRNS)
This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit.
For grayscale PNGs, r, g and b will all 3 be set to the same.
When decoding, by default you can ignore this information, since LodePNG sets
pixels with this key to transparent already in the raw RGBA output.
The color key is only supported for color types 0 and 2.
*/
unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/
unsigned key_r; /*red/grayscale component of color key*/
unsigned key_g; /*green component of color key*/
unsigned key_b; /*blue component of color key*/
} LodePNGColorMode;
/*init, cleanup and copy functions to use with this struct*/
void lodepng_color_mode_init(LodePNGColorMode * info);
void lodepng_color_mode_cleanup(LodePNGColorMode * info);
/*return value is error code (0 means no error)*/
unsigned lodepng_color_mode_copy(LodePNGColorMode * dest, const LodePNGColorMode * source);
/* Makes a temporary LodePNGColorMode that does not need cleanup (no palette) */
LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth);
void lodepng_palette_clear(LodePNGColorMode * info);
/*add 1 color to the palette*/
unsigned lodepng_palette_add(LodePNGColorMode * info,
unsigned char r, unsigned char g, unsigned char b, unsigned char a);
/*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/
unsigned lodepng_get_bpp(const LodePNGColorMode * info);
/*get the amount of color channels used, based on colortype in the struct.
If a palette is used, it counts as 1 channel.*/
unsigned lodepng_get_channels(const LodePNGColorMode * info);
/*is it a grayscale type? (only colortype 0 or 4)*/
unsigned lodepng_is_greyscale_type(const LodePNGColorMode * info);
/*has it got an alpha channel? (only colortype 2 or 6)*/
unsigned lodepng_is_alpha_type(const LodePNGColorMode * info);
/*has it got a palette? (only colortype 3)*/
unsigned lodepng_is_palette_type(const LodePNGColorMode * info);
/*only returns true if there is a palette and there is a value in the palette with alpha < 255.
Loops through the palette to check this.*/
unsigned lodepng_has_palette_alpha(const LodePNGColorMode * info);
/*
Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image.
Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels).
Returns false if the image can only have opaque pixels.
In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values,
or if "key_defined" is true.
*/
unsigned lodepng_can_have_alpha(const LodePNGColorMode * info);
/*Returns the byte size of a raw image buffer with given width, height and color mode*/
size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode * color);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*The information of a Time chunk in PNG.*/
typedef struct _LodePNGTime {
unsigned year; /*2 bytes used (0-65535)*/
unsigned month; /*1-12*/
unsigned day; /*1-31*/
unsigned hour; /*0-23*/
unsigned minute; /*0-59*/
unsigned second; /*0-60 (to allow for leap seconds)*/
} LodePNGTime;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*Information about the PNG image, except pixels, width and height.*/
typedef struct _LodePNGInfo {
/*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/
unsigned compression_method;/*compression method of the original file. Always 0.*/
unsigned filter_method; /*filter method of the original file*/
unsigned interlace_method; /*interlace method of the original file: 0=none, 1=Adam7*/
LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*
Suggested background color chunk (bKGD)
This uses the same color mode and bit depth as the PNG (except no alpha channel),
with values truncated to the bit depth in the unsigned integer.
For grayscale and palette PNGs, the value is stored in background_r. The values
in background_g and background_b are then unused.
So when decoding, you may get these in a different color mode than the one you requested
for the raw pixels.
When encoding with auto_convert, you must use the color model defined in info_png.color for
these values. The encoder normally ignores info_png.color when auto_convert is on, but will
use it to interpret these values (and convert copies of them to its chosen color model).
When encoding, avoid setting this to an expensive color, such as a non-gray value
when the image is gray, or the compression will be worse since it will be forced to
write the PNG with a more expensive color mode (when auto_convert is on).
The decoder does not use this background color to edit the color of pixels. This is a
completely optional metadata feature.
*/
unsigned background_defined; /*is a suggested background color given?*/
unsigned background_r; /*red/gray/palette component of suggested background color*/
unsigned background_g; /*green component of suggested background color*/
unsigned background_b; /*blue component of suggested background color*/
/*
Non-international text chunks (tEXt and zTXt)
The char** arrays each contain num strings. The actual messages are in
text_strings, while text_keys are keywords that give a short description what
the actual text represents, e.g. Title, Author, Description, or anything else.
All the string fields below including strings, keys, names and language tags are null terminated.
The PNG specification uses null characters for the keys, names and tags, and forbids null
characters to appear in the main text which is why we can use null termination everywhere here.
A keyword is minimum 1 character and maximum 79 characters long (plus the
additional null terminator). It's discouraged to use a single line length
longer than 79 characters for texts.
Don't allocate these text buffers yourself. Use the init/cleanup functions
correctly and use lodepng_add_text and lodepng_clear_text.
Standard text chunk keywords and strings are encoded using Latin-1.
*/
size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/
char ** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/
char ** text_strings; /*the actual text*/
/*
International text chunks (iTXt)
Similar to the non-international text chunks, but with additional strings
"langtags" and "transkeys", and the following text encodings are used:
keys: Latin-1, langtags: ASCII, transkeys and strings: UTF-8.
keys must be 1-79 characters (plus the additional null terminator), the other
strings are any length.
*/
size_t itext_num; /*the amount of international texts in this PNG*/
char ** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/
char ** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/
char ** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/
char ** itext_strings; /*the actual international text - UTF-8 string*/
/*time chunk (tIME)*/
unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/
LodePNGTime time;
/*phys chunk (pHYs)*/
unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/
unsigned phys_x; /*pixels per unit in x direction*/
unsigned phys_y; /*pixels per unit in y direction*/
unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/
/*
Color profile related chunks: gAMA, cHRM, sRGB, iCPP
LodePNG does not apply any color conversions on pixels in the encoder or decoder and does not interpret these color
profile values. It merely passes on the information. If you wish to use color profiles and convert colors, please
use these values with a color management library.
See the PNG, ICC and sRGB specifications for more information about the meaning of these values.
*/
/* gAMA chunk: optional, overridden by sRGB or iCCP if those are present. */
unsigned gama_defined; /* Whether a gAMA chunk is present (0 = not present, 1 = present). */
unsigned gama_gamma; /* Gamma exponent times 100000 */
/* cHRM chunk: optional, overridden by sRGB or iCCP if those are present. */
unsigned chrm_defined; /* Whether a cHRM chunk is present (0 = not present, 1 = present). */
unsigned chrm_white_x; /* White Point x times 100000 */
unsigned chrm_white_y; /* White Point y times 100000 */
unsigned chrm_red_x; /* Red x times 100000 */
unsigned chrm_red_y; /* Red y times 100000 */
unsigned chrm_green_x; /* Green x times 100000 */
unsigned chrm_green_y; /* Green y times 100000 */
unsigned chrm_blue_x; /* Blue x times 100000 */
unsigned chrm_blue_y; /* Blue y times 100000 */
/*
sRGB chunk: optional. May not appear at the same time as iCCP.
If gAMA is also present gAMA must contain value 45455.
If cHRM is also present cHRM must contain respectively 31270,32900,64000,33000,30000,60000,15000,6000.
*/
unsigned srgb_defined; /* Whether an sRGB chunk is present (0 = not present, 1 = present). */
unsigned srgb_intent; /* Rendering intent: 0=perceptual, 1=rel. colorimetric, 2=saturation, 3=abs. colorimetric */
/*
iCCP chunk: optional. May not appear at the same time as sRGB.
LodePNG does not parse or use the ICC profile (except its color space header field for an edge case), a
separate library to handle the ICC data (not included in LodePNG) format is needed to use it for color
management and conversions.
For encoding, if iCCP is present, gAMA and cHRM are recommended to be added as well with values that match the ICC
profile as closely as possible, if you wish to do this you should provide the correct values for gAMA and cHRM and
enable their '_defined' flags since LodePNG will not automatically compute them from the ICC profile.
For encoding, the ICC profile is required by the PNG specification to be an "RGB" profile for non-gray
PNG color types and a "GRAY" profile for gray PNG color types. If you disable auto_convert, you must ensure
the ICC profile type matches your requested color type, else the encoder gives an error. If auto_convert is
enabled (the default), and the ICC profile is not a good match for the pixel data, this will result in an encoder
error if the pixel data has non-gray pixels for a GRAY profile, or a silent less-optimal compression of the pixel
data if the pixels could be encoded as grayscale but the ICC profile is RGB.
To avoid this do not set an ICC profile in the image unless there is a good reason for it, and when doing so
make sure you compute it carefully to avoid the above problems.
*/
unsigned iccp_defined; /* Whether an iCCP chunk is present (0 = not present, 1 = present). */
char * iccp_name; /* Null terminated string with profile name, 1-79 bytes */
/*
The ICC profile in iccp_profile_size bytes.
Don't allocate this buffer yourself. Use the init/cleanup functions
correctly and use lodepng_set_icc and lodepng_clear_icc.
*/
unsigned char * iccp_profile;
unsigned iccp_profile_size; /* The size of iccp_profile in bytes */
/* End of color profile related chunks */
/*
unknown chunks: chunks not known by LodePNG, passed on byte for byte.
There are 3 buffers, one for each position in the PNG where unknown chunks can appear.
Each buffer contains all unknown chunks for that position consecutively.
The 3 positions are:
0: between IHDR and PLTE, 1: between PLTE and IDAT, 2: between IDAT and IEND.
For encoding, do not store critical chunks or known chunks that are enabled with a "_defined" flag
above in here, since the encoder will blindly follow this and could then encode an invalid PNG file
(such as one with two IHDR chunks or the disallowed combination of sRGB with iCCP). But do use
this if you wish to store an ancillary chunk that is not supported by LodePNG (such as sPLT or hIST),
or any non-standard PNG chunk.
Do not allocate or traverse this data yourself. Use the chunk traversing functions declared
later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct.
*/
unsigned char * unknown_chunks_data[3];
size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} LodePNGInfo;
/*init, cleanup and copy functions to use with this struct*/
void lodepng_info_init(LodePNGInfo * info);
void lodepng_info_cleanup(LodePNGInfo * info);
/*return value is error code (0 means no error)*/
unsigned lodepng_info_copy(LodePNGInfo * dest, const LodePNGInfo * source);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
unsigned lodepng_add_text(LodePNGInfo * info, const char * key, const char * str); /*push back both texts at once*/
void lodepng_clear_text(LodePNGInfo * info); /*use this to clear the texts again after you filled them in*/
unsigned lodepng_add_itext(LodePNGInfo * info, const char * key, const char * langtag,
const char * transkey, const char * str); /*push back the 4 texts of 1 chunk at once*/
void lodepng_clear_itext(LodePNGInfo * info); /*use this to clear the itexts again after you filled them in*/
/*replaces if exists*/
unsigned lodepng_set_icc(LodePNGInfo * info, const char * name, const unsigned char * profile, unsigned profile_size);
void lodepng_clear_icc(LodePNGInfo * info); /*use this to clear the texts again after you filled them in*/
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*
Converts raw buffer from one color type to another color type, based on
LodePNGColorMode structs to describe the input and output color type.
See the reference manual at the end of this header file to see which color conversions are supported.
return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported)
The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel
of the output color type (lodepng_get_bpp).
For < 8 bpp images, there should not be padding bits at the end of scanlines.
For 16-bit per channel colors, uses big endian format like PNG does.
Return value is LodePNG error code
*/
unsigned lodepng_convert(unsigned char * out, const unsigned char * in,
const LodePNGColorMode * mode_out, const LodePNGColorMode * mode_in,
unsigned w, unsigned h);
#ifdef LODEPNG_COMPILE_DECODER
/*
Settings for the decoder. This contains settings for the PNG and the Zlib
decoder, but not the Info settings from the Info structs.
*/
typedef struct _LodePNGDecoderSettings {
LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/
/* Check LodePNGDecompressSettings for more ignorable errors such as ignore_adler32 */
unsigned ignore_crc; /*ignore CRC checksums*/
unsigned ignore_critical; /*ignore unknown critical chunks*/
unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/
/* TODO: make a system involving warnings with levels and a strict mode instead. Other potentially recoverable
errors: srgb rendering intent value, size of content of ancillary chunks, more than 79 characters for some
strings, placement/combination rules for ancillary chunks, crc of unknown chunks, allowed characters
in string keys, etc... */
unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/
/*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/
unsigned remember_unknown_chunks;
/* maximum size for decompressed text chunks. If a text chunk's text is larger than this, an error is returned,
unless reading text chunks is disabled or this limit is set higher or disabled. Set to 0 to allow any size.
By default it is a value that prevents unreasonably large strings from hogging memory. */
size_t max_text_size;
/* maximum size for compressed ICC chunks. If the ICC profile is larger than this, an error will be returned. Set to
0 to allow any size. By default this is a value that prevents ICC profiles that would be much larger than any
legitimate profile could be to hog memory. */
size_t max_icc_size;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} LodePNGDecoderSettings;
void lodepng_decoder_settings_init(LodePNGDecoderSettings * settings);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/
typedef enum _LodePNGFilterStrategy {
/*every filter at zero*/
LFS_ZERO = 0,
/*every filter at 1, 2, 3 or 4 (paeth), unlike LFS_ZERO not a good choice, but for testing*/
LFS_ONE = 1,
LFS_TWO = 2,
LFS_THREE = 3,
LFS_FOUR = 4,
/*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/
LFS_MINSUM,
/*Use the filter type that gives smallest Shannon entropy for this scanline. Depending
on the image, this is better or worse than minsum.*/
LFS_ENTROPY,
/*
Brute-force-search PNG filters by compressing each filter for each scanline.
Experimental, very slow, and only rarely gives better compression than MINSUM.
*/
LFS_BRUTE_FORCE,
/*use predefined_filters buffer: you specify the filter type for each scanline*/
LFS_PREDEFINED
} LodePNGFilterStrategy;
/*Gives characteristics about the integer RGBA colors of the image (count, alpha channel usage, bit depth, ...),
which helps decide which color model to use for encoding.
Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/
typedef struct _LodePNGColorStats {
unsigned colored; /*not grayscale*/
unsigned key; /*image is not opaque and color key is possible instead of full alpha*/
unsigned short key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/
unsigned short key_g;
unsigned short key_b;
unsigned alpha; /*image is not opaque and alpha channel or alpha palette required*/
unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16 or allow_palette is disabled.*/
unsigned char
palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order, only valid when numcolors is valid*/
unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for grayscale only. 16 if 16-bit per channel required.*/
size_t numpixels;
/*user settings for computing/using the stats*/
unsigned allow_palette; /*default 1. if 0, disallow choosing palette colortype in auto_choose_color, and don't count numcolors*/
unsigned allow_greyscale; /*default 1. if 0, choose RGB or RGBA even if the image only has gray colors*/
} LodePNGColorStats;
void lodepng_color_stats_init(LodePNGColorStats * stats);
/*Get a LodePNGColorStats of the image. The stats must already have been inited.
Returns error code (e.g. alloc fail) or 0 if ok.*/
unsigned lodepng_compute_color_stats(LodePNGColorStats * stats,
const unsigned char * image, unsigned w, unsigned h,
const LodePNGColorMode * mode_in);
/*Settings for the encoder.*/
typedef struct _LodePNGEncoderSettings {
LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/
unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/
/*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than
8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to
completely follow the official PNG heuristic, filter_palette_zero must be true and
filter_strategy must be LFS_MINSUM*/
unsigned filter_palette_zero;
/*Which filter strategy to use when not using zeroes due to filter_palette_zero.
Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/
LodePNGFilterStrategy filter_strategy;
/*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with
the same length as the amount of scanlines in the image, and each value must <= 5. You
have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero
must be set to 0 to ensure this is also used on palette or low bitdepth images.*/
const unsigned char * predefined_filters;
/*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette).
If colortype is 3, PLTE is _always_ created.*/
unsigned force_palette;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*add LodePNG identifier and version as a text chunk, for debugging*/
unsigned add_id;
/*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/
unsigned text_compression;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} LodePNGEncoderSettings;
void lodepng_encoder_settings_init(LodePNGEncoderSettings * settings);
#endif /*LODEPNG_COMPILE_ENCODER*/
#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
/*The settings, state and information for extended encoding and decoding.*/
typedef struct _LodePNGState {
#ifdef LODEPNG_COMPILE_DECODER
LodePNGDecoderSettings decoder; /*the decoding settings*/
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
LodePNGEncoderSettings encoder; /*the encoding settings*/
#endif /*LODEPNG_COMPILE_ENCODER*/
LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/
LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/
unsigned error;
} LodePNGState;
/*init, cleanup and copy functions to use with this struct*/
void lodepng_state_init(LodePNGState * state);
void lodepng_state_cleanup(LodePNGState * state);
void lodepng_state_copy(LodePNGState * dest, const LodePNGState * source);
#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
#ifdef LODEPNG_COMPILE_DECODER
/*
Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and
getting much more information about the PNG image and color mode.
*/
unsigned lodepng_decode(unsigned char ** out, unsigned * w, unsigned * h,
LodePNGState * state,
const unsigned char * in, size_t insize);
/*
Read the PNG header, but not the actual data. This returns only the information
that is in the IHDR chunk of the PNG, such as width, height and color type. The
information is placed in the info_png field of the LodePNGState.
*/
unsigned lodepng_inspect(unsigned * w, unsigned * h,
LodePNGState * state,
const unsigned char * in, size_t insize);
#endif /*LODEPNG_COMPILE_DECODER*/
/*
Reads one metadata chunk (other than IHDR) of the PNG file and outputs what it
read in the state. Returns error code on failure.
Use lodepng_inspect first with a new state, then e.g. lodepng_chunk_find_const
to find the desired chunk type, and if non null use lodepng_inspect_chunk (with
chunk_pointer - start_of_file as pos).
Supports most metadata chunks from the PNG standard (gAMA, bKGD, tEXt, ...).
Ignores unsupported, unknown, non-metadata or IHDR chunks (without error).
Requirements: &in[pos] must point to start of a chunk, must use regular
lodepng_inspect first since format of most other chunks depends on IHDR, and if
there is a PLTE chunk, that one must be inspected before tRNS or bKGD.
*/
unsigned lodepng_inspect_chunk(LodePNGState * state, size_t pos,
const unsigned char * in, size_t insize);
#ifdef LODEPNG_COMPILE_ENCODER
/*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/
unsigned lodepng_encode(unsigned char ** out, size_t * outsize,
const unsigned char * image, unsigned w, unsigned h,
LodePNGState * state);
#endif /*LODEPNG_COMPILE_ENCODER*/
/*
The lodepng_chunk functions are normally not needed, except to traverse the
unknown chunks stored in the LodePNGInfo struct, or add new ones to it.
It also allows traversing the chunks of an encoded PNG file yourself.
The chunk pointer always points to the beginning of the chunk itself, that is
the first byte of the 4 length bytes.
In the PNG file format, chunks have the following format:
-4 bytes length: length of the data of the chunk in bytes (chunk itself is 12 bytes longer)
-4 bytes chunk type (ASCII a-z,A-Z only, see below)
-length bytes of data (may be 0 bytes if length was 0)
-4 bytes of CRC, computed on chunk name + data
The first chunk starts at the 8th byte of the PNG file, the entire rest of the file
exists out of concatenated chunks with the above format.
PNG standard chunk ASCII naming conventions:
-First byte: uppercase = critical, lowercase = ancillary
-Second byte: uppercase = public, lowercase = private
-Third byte: must be uppercase
-Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy
*/
/*
Gets the length of the data of the chunk. Total chunk length has 12 bytes more.
There must be at least 4 bytes to read from. If the result value is too large,
it may be corrupt data.
*/
unsigned lodepng_chunk_length(const unsigned char * chunk);
/*puts the 4-byte type in null terminated string*/
void lodepng_chunk_type(char type[5], const unsigned char * chunk);
/*check if the type is the given type*/
unsigned char lodepng_chunk_type_equals(const unsigned char * chunk, const char * type);
/*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/
unsigned char lodepng_chunk_ancillary(const unsigned char * chunk);
/*0: public, 1: private (see PNG standard)*/
unsigned char lodepng_chunk_private(const unsigned char * chunk);
/*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/
unsigned char lodepng_chunk_safetocopy(const unsigned char * chunk);
/*get pointer to the data of the chunk, where the input points to the header of the chunk*/
unsigned char * lodepng_chunk_data(unsigned char * chunk);
const unsigned char * lodepng_chunk_data_const(const unsigned char * chunk);
/*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/
unsigned lodepng_chunk_check_crc(const unsigned char * chunk);
/*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/
void lodepng_chunk_generate_crc(unsigned char * chunk);
/*
Iterate to next chunks, allows iterating through all chunks of the PNG file.
Input must be at the beginning of a chunk (result of a previous lodepng_chunk_next call,
or the 8th byte of a PNG file which always has the first chunk), or alternatively may
point to the first byte of the PNG file (which is not a chunk but the magic header, the
function will then skip over it and return the first real chunk).
Will output pointer to the start of the next chunk, or at or beyond end of the file if there
is no more chunk after this or possibly if the chunk is corrupt.
Start this process at the 8th byte of the PNG file.
In a non-corrupt PNG file, the last chunk should have name "IEND".
*/
unsigned char * lodepng_chunk_next(unsigned char * chunk, unsigned char * end);
const unsigned char * lodepng_chunk_next_const(const unsigned char * chunk, const unsigned char * end);
/*Finds the first chunk with the given type in the range [chunk, end), or returns NULL if not found.*/
unsigned char * lodepng_chunk_find(unsigned char * chunk, unsigned char * end, const char type[5]);
const unsigned char * lodepng_chunk_find_const(const unsigned char * chunk, const unsigned char * end,
const char type[5]);
/*
Appends chunk to the data in out. The given chunk should already have its chunk header.
The out variable and outsize are updated to reflect the new reallocated buffer.
Returns error code (0 if it went ok)
*/
unsigned lodepng_chunk_append(unsigned char ** out, size_t * outsize, const unsigned char * chunk);
/*
Appends new chunk to out. The chunk to append is given by giving its length, type
and data separately. The type is a 4-letter string.
The out variable and outsize are updated to reflect the new reallocated buffer.
Return error code (0 if it went ok)
*/
unsigned lodepng_chunk_create(unsigned char ** out, size_t * outsize, unsigned length,
const char * type, const unsigned char * data);
/*Calculate CRC32 of buffer*/
unsigned lodepng_crc32(const unsigned char * buf, size_t len);
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ZLIB
/*
This zlib part can be used independently to zlib compress and decompress a
buffer. It cannot be used to create gzip files however, and it only supports the
part of zlib that is required for PNG, it does not support dictionaries.
*/
#ifdef LODEPNG_COMPILE_DECODER
/*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/
unsigned lodepng_inflate(unsigned char ** out, size_t * outsize,
const unsigned char * in, size_t insize,
const LodePNGDecompressSettings * settings);
/*
Decompresses Zlib data. Reallocates the out buffer and appends the data. The
data must be according to the zlib specification.
Either, *out must be NULL and *outsize must be 0, or, *out must be a valid
buffer and *outsize its size in bytes. out must be freed by user after usage.
*/
unsigned lodepng_zlib_decompress(unsigned char ** out, size_t * outsize,
const unsigned char * in, size_t insize,
const LodePNGDecompressSettings * settings);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/*
Compresses data with Zlib. Reallocates the out buffer and appends the data.
Zlib adds a small header and trailer around the deflate data.
The data is output in the format of the zlib specification.
Either, *out must be NULL and *outsize must be 0, or, *out must be a valid
buffer and *outsize its size in bytes. out must be freed by user after usage.
*/
unsigned lodepng_zlib_compress(unsigned char ** out, size_t * outsize,
const unsigned char * in, size_t insize,
const LodePNGCompressSettings * settings);
/*
Find length-limited Huffman code for given frequencies. This function is in the
public interface only for tests, it's used internally by lodepng_deflate.
*/
unsigned lodepng_huffman_code_lengths(unsigned * lengths, const unsigned * frequencies,
size_t numcodes, unsigned maxbitlen);
/*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/
unsigned lodepng_deflate(unsigned char ** out, size_t * outsize,
const unsigned char * in, size_t insize,
const LodePNGCompressSettings * settings);
#endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_ZLIB*/
#ifdef LODEPNG_COMPILE_DISK
/*
Load a file from disk into buffer. The function allocates the out buffer, and
after usage you should free it.
out: output parameter, contains pointer to loaded buffer.
outsize: output parameter, size of the allocated out buffer
filename: the path to the file to load
return value: error code (0 means ok)
*/
unsigned lodepng_load_file(unsigned char ** out, size_t * outsize, const char * filename);
/*
Save a file from buffer to disk. Warning, if it exists, this function overwrites
the file without warning!
buffer: the buffer to write
buffersize: size of the buffer to write
filename: the path to the file to save to
return value: error code (0 means ok)
*/
unsigned lodepng_save_file(const unsigned char * buffer, size_t buffersize, const char * filename);
#endif /*LODEPNG_COMPILE_DISK*/
#ifdef LODEPNG_COMPILE_CPP
/* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */
namespace lodepng
{
#ifdef LODEPNG_COMPILE_PNG
class State : public LodePNGState
{
public:
State();
State(const State & other);
~State();
State & operator=(const State & other);
};
#ifdef LODEPNG_COMPILE_DECODER
/* Same as other lodepng::decode, but using a State for more settings and information. */
unsigned decode(std::vector<unsigned char> & out, unsigned & w, unsigned & h,
State & state,
const unsigned char * in, size_t insize);
unsigned decode(std::vector<unsigned char> & out, unsigned & w, unsigned & h,
State & state,
const std::vector<unsigned char> & in);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/* Same as other lodepng::encode, but using a State for more settings and information. */
unsigned encode(std::vector<unsigned char> & out,
const unsigned char * in, unsigned w, unsigned h,
State & state);
unsigned encode(std::vector<unsigned char> & out,
const std::vector<unsigned char> & in, unsigned w, unsigned h,
State & state);
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_DISK
/*
Load a file from disk into an std::vector.
return value: error code (0 means ok)
*/
unsigned load_file(std::vector<unsigned char> & buffer, const std::string & filename);
/*
Save the binary data in an std::vector to a file on disk. The file is overwritten
without warning.
*/
unsigned save_file(const std::vector<unsigned char> & buffer, const std::string & filename);
#endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_PNG */
#ifdef LODEPNG_COMPILE_ZLIB
#ifdef LODEPNG_COMPILE_DECODER
/* Zlib-decompress an unsigned char buffer */
unsigned decompress(std::vector<unsigned char> & out, const unsigned char * in, size_t insize,
const LodePNGDecompressSettings & settings = lodepng_default_decompress_settings);
/* Zlib-decompress an std::vector */
unsigned decompress(std::vector<unsigned char> & out, const std::vector<unsigned char> & in,
const LodePNGDecompressSettings & settings = lodepng_default_decompress_settings);
#endif /* LODEPNG_COMPILE_DECODER */
#ifdef LODEPNG_COMPILE_ENCODER
/* Zlib-compress an unsigned char buffer */
unsigned compress(std::vector<unsigned char> & out, const unsigned char * in, size_t insize,
const LodePNGCompressSettings & settings = lodepng_default_compress_settings);
/* Zlib-compress an std::vector */
unsigned compress(std::vector<unsigned char> & out, const std::vector<unsigned char> & in,
const LodePNGCompressSettings & settings = lodepng_default_compress_settings);
#endif /* LODEPNG_COMPILE_ENCODER */
#endif /* LODEPNG_COMPILE_ZLIB */
} /* namespace lodepng */
#endif /*LODEPNG_COMPILE_CPP*/
/*
TODO:
[.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often
[.] check compatibility with various compilers - done but needs to be redone for every newer version
[X] converting color to 16-bit per channel types
[X] support color profile chunk types (but never let them touch RGB values by default)
[ ] support all public PNG chunk types (almost done except sBIT, sPLT and hIST)
[ ] make sure encoder generates no chunks with size > (2^31)-1
[ ] partial decoding (stream processing)
[X] let the "isFullyOpaque" function check color keys and transparent palettes too
[X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl"
[ ] allow treating some errors like warnings, when image is recoverable (e.g. 69, 57, 58)
[ ] make warnings like: oob palette, checksum fail, data after iend, wrong/unknown crit chunk, no null terminator in text, ...
[ ] error messages with line numbers (and version)
[ ] errors in state instead of as return code?
[ ] new errors/warnings like suspiciously big decompressed ztxt or iccp chunk
[ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes
[ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ...
[ ] allow user to give data (void*) to custom allocator
[X] provide alternatives for C library functions not present on some platforms (memcpy, ...)
*/
#endif /*LV_USE_LODEPNG*/
#endif /*LODEPNG_H inclusion guard*/
/*
LodePNG Documentation
---------------------
0. table of contents
--------------------
1. about
1.1. supported features
1.2. features not supported
2. C and C++ version
3. security
4. decoding
5. encoding
6. color conversions
6.1. PNG color types
6.2. color conversions
6.3. padding bits
6.4. A note about 16-bits per channel and endianness
7. error values
8. chunks and PNG editing
9. compiler support
10. examples
10.1. decoder C++ example
10.2. decoder C example
11. state settings reference
12. changes
13. contact information
1. about
--------
PNG is a file format to store raster images losslessly with good compression,
supporting different color types and alpha channel.
LodePNG is a PNG codec according to the Portable Network Graphics (PNG)
Specification (Second Edition) - W3C Recommendation 10 November 2003.
The specifications used are:
*) Portable Network Graphics (PNG) Specification (Second Edition):
http://www.w3.org/TR/2003/REC-PNG-20031110
*) RFC 1950 ZLIB Compressed Data Format version 3.3:
http://www.gzip.org/zlib/rfc-zlib.html
*) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3:
http://www.gzip.org/zlib/rfc-deflate.html
The most recent version of LodePNG can currently be found at
http://lodev.org/lodepng/
LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds
extra functionality.
LodePNG exists out of two files:
-lodepng.h: the header file for both C and C++
-lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage
If you want to start using LodePNG right away without reading this doc, get the
examples from the LodePNG website to see how to use it in code, or check the
smaller examples in chapter 13 here.
LodePNG is simple but only supports the basic requirements. To achieve
simplicity, the following design choices were made: There are no dependencies
on any external library. There are functions to decode and encode a PNG with
a single function call, and extended versions of these functions taking a
LodePNGState struct allowing to specify or get more information. By default
the colors of the raw image are always RGB or RGBA, no matter what color type
the PNG file uses. To read and write files, there are simple functions to
convert the files to/from buffers in memory.
This all makes LodePNG suitable for loading textures in games, demos and small
programs, ... It's less suitable for full fledged image editors, loading PNGs
over network (it requires all the image data to be available before decoding can
begin), life-critical systems, ...
1.1. supported features
-----------------------
The following features are supported by the decoder:
*) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image,
or the same color type as the PNG
*) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image
*) Adam7 interlace and deinterlace for any color type
*) loading the image from harddisk or decoding it from a buffer from other sources than harddisk
*) support for alpha channels, including RGBA color modelete,translucent palettes and color keying
*) zlib decompression (inflate)
*) zlib compression (deflate)
*) CRC32 and ADLER32 checksums
*) colorimetric color profile conversions: currently experimentally available in lodepng_util.cpp only,
plus alternatively ability to pass on chroma/gamma/ICC profile information to other color management system.
*) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks.
*) the following chunks are supported by both encoder and decoder:
IHDR: header information
PLTE: color palette
IDAT: pixel data
IEND: the final chunk
tRNS: transparency for palettized images
tEXt: textual information
zTXt: compressed textual information
iTXt: international textual information
bKGD: suggested background color
pHYs: physical dimensions
tIME: modification time
cHRM: RGB chromaticities
gAMA: RGB gamma correction
iCCP: ICC color profile
sRGB: rendering intent
1.2. features not supported
---------------------------
The following features are _not_ supported:
*) some features needed to make a conformant PNG-Editor might be still missing.
*) partial loading/stream processing. All data must be available and is processed in one call.
*) The following public chunks are not (yet) supported but treated as unknown chunks by LodePNG:
sBIT
hIST
sPLT
2. C and C++ version
--------------------
The C version uses buffers allocated with alloc that you need to free()
yourself. You need to use init and cleanup functions for each struct whenever
using a struct from the C version to avoid exploits and memory leaks.
The C++ version has extra functions with std::vectors in the interface and the
lodepng::State class which is a LodePNGState with constructor and destructor.
These files work without modification for both C and C++ compilers because all
the additional C++ code is in "#ifdef __cplusplus" blocks that make C-compilers
ignore it, and the C code is made to compile both with strict ISO C90 and C++.
To use the C++ version, you need to rename the source file to lodepng.cpp
(instead of lodepng.c), and compile it with a C++ compiler.
To use the C version, you need to rename the source file to lodepng.c (instead
of lodepng.cpp), and compile it with a C compiler.
3. Security
-----------
Even if carefully designed, it's always possible that LodePNG contains possible
exploits. If you discover one, please let me know, and it will be fixed.
When using LodePNG, care has to be taken with the C version of LodePNG, as well
as the C-style structs when working with C++. The following conventions are used
for all C-style structs:
-if a struct has a corresponding init function, always call the init function when making a new one
-if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks
-if a struct has a corresponding copy function, use the copy function instead of "=".
The destination must also be inited already.
4. Decoding
-----------
Decoding converts a PNG compressed image to a raw pixel buffer.
Most documentation on using the decoder is at its declarations in the header
above. For C, simple decoding can be done with functions such as
lodepng_decode32, and more advanced decoding can be done with the struct
LodePNGState and lodepng_decode. For C++, all decoding can be done with the
various lodepng::decode functions, and lodepng::State can be used for advanced
features.
When using the LodePNGState, it uses the following fields for decoding:
*) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here
*) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get
*) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use
LodePNGInfo info_png
--------------------
After decoding, this contains extra information of the PNG image, except the actual
pixels, width and height because these are already gotten directly from the decoder
functions.
It contains for example the original color type of the PNG image, text comments,
suggested background color, etc... More details about the LodePNGInfo struct are
at its declaration documentation.
LodePNGColorMode info_raw
-------------------------
When decoding, here you can specify which color type you want
the resulting raw image to be. If this is different from the colortype of the
PNG, then the decoder will automatically convert the result. This conversion
always works, except if you want it to convert a color PNG to grayscale or to
a palette with missing colors.
By default, 32-bit color is used for the result.
LodePNGDecoderSettings decoder
------------------------------
The settings can be used to ignore the errors created by invalid CRC and Adler32
chunks, and to disable the decoding of tEXt chunks.
There's also a setting color_convert, true by default. If false, no conversion
is done, the resulting data will be as it was in the PNG (after decompression)
and you'll have to puzzle the colors of the pixels together yourself using the
color type information in the LodePNGInfo.
5. Encoding
-----------
Encoding converts a raw pixel buffer to a PNG compressed image.
Most documentation on using the encoder is at its declarations in the header
above. For C, simple encoding can be done with functions such as
lodepng_encode32, and more advanced decoding can be done with the struct
LodePNGState and lodepng_encode. For C++, all encoding can be done with the
various lodepng::encode functions, and lodepng::State can be used for advanced
features.
Like the decoder, the encoder can also give errors. However it gives less errors
since the encoder input is trusted, the decoder input (a PNG image that could
be forged by anyone) is not trusted.
When using the LodePNGState, it uses the following fields for encoding:
*) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be.
*) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has
*) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use
LodePNGInfo info_png
--------------------
When encoding, you use this the opposite way as when decoding: for encoding,
you fill in the values you want the PNG to have before encoding. By default it's
not needed to specify a color type for the PNG since it's automatically chosen,
but it's possible to choose it yourself given the right settings.
The encoder will not always exactly match the LodePNGInfo struct you give,
it tries as close as possible. Some things are ignored by the encoder. The
encoder uses, for example, the following settings from it when applicable:
colortype and bitdepth, text chunks, time chunk, the color key, the palette, the
background color, the interlace method, unknown chunks, ...
When encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk.
If the palette contains any colors for which the alpha channel is not 255 (so
there are translucent colors in the palette), it'll add a tRNS chunk.
LodePNGColorMode info_raw
-------------------------
You specify the color type of the raw image that you give to the input here,
including a possible transparent color key and palette you happen to be using in
your raw image data.
By default, 32-bit color is assumed, meaning your input has to be in RGBA
format with 4 bytes (unsigned chars) per pixel.
LodePNGEncoderSettings encoder
------------------------------
The following settings are supported (some are in sub-structs):
*) auto_convert: when this option is enabled, the encoder will
automatically choose the smallest possible color mode (including color key) that
can encode the colors of all pixels without information loss.
*) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree,
2 = dynamic huffman tree (best compression). Should be 2 for proper
compression.
*) use_lz77: whether or not to use LZ77 for compressed block types. Should be
true for proper compression.
*) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value
2048 by default, but can be set to 32768 for better, but slow, compression.
*) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE
chunk if force_palette is true. This can used as suggested palette to convert
to by viewers that don't support more than 256 colors (if those still exist)
*) add_id: add text chunk "Encoder: LodePNG <version>" to the image.
*) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks.
zTXt chunks use zlib compression on the text. This gives a smaller result on
large texts but a larger result on small texts (such as a single program name).
It's all tEXt or all zTXt though, there's no separate setting per text yet.
6. color conversions
--------------------
An important thing to note about LodePNG, is that the color type of the PNG, and
the color type of the raw image, are completely independent. By default, when
you decode a PNG, you get the result as a raw image in the color type you want,
no matter whether the PNG was encoded with a palette, grayscale or RGBA color.
And if you encode an image, by default LodePNG will automatically choose the PNG
color type that gives good compression based on the values of colors and amount
of colors in the image. It can be configured to let you control it instead as
well, though.
To be able to do this, LodePNG does conversions from one color mode to another.
It can convert from almost any color type to any other color type, except the
following conversions: RGB to grayscale is not supported, and converting to a
palette when the palette doesn't have a required color is not supported. This is
not supported on purpose: this is information loss which requires a color
reduction algorithm that is beyond the scope of a PNG encoder (yes, RGB to gray
is easy, but there are multiple ways if you want to give some channels more
weight).
By default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB
color, no matter what color type the PNG has. And by default when encoding,
LodePNG automatically picks the best color model for the output PNG, and expects
the input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control
the color format of the images yourself, you can skip this chapter.
6.1. PNG color types
--------------------
A PNG image can have many color types, ranging from 1-bit color to 64-bit color,
as well as palettized color modes. After the zlib decompression and unfiltering
in the PNG image is done, the raw pixel data will have that color type and thus
a certain amount of bits per pixel. If you want the output raw image after
decoding to have another color type, a conversion is done by LodePNG.
The PNG specification gives the following color types:
0: grayscale, bit depths 1, 2, 4, 8, 16
2: RGB, bit depths 8 and 16
3: palette, bit depths 1, 2, 4 and 8
4: grayscale with alpha, bit depths 8 and 16
6: RGBA, bit depths 8 and 16
Bit depth is the amount of bits per pixel per color channel. So the total amount
of bits per pixel is: amount of channels * bitdepth.
6.2. color conversions
----------------------
As explained in the sections about the encoder and decoder, you can specify
color types and bit depths in info_png and info_raw to change the default
behaviour.
If, when decoding, you want the raw image to be something else than the default,
you need to set the color type and bit depth you want in the LodePNGColorMode,
or the parameters colortype and bitdepth of the simple decoding function.
If, when encoding, you use another color type than the default in the raw input
image, you need to specify its color type and bit depth in the LodePNGColorMode
of the raw image, or use the parameters colortype and bitdepth of the simple
encoding function.
If, when encoding, you don't want LodePNG to choose the output PNG color type
but control it yourself, you need to set auto_convert in the encoder settings
to false, and specify the color type you want in the LodePNGInfo of the
encoder (including palette: it can generate a palette if auto_convert is true,
otherwise not).
If the input and output color type differ (whether user chosen or auto chosen),
LodePNG will do a color conversion, which follows the rules below, and may
sometimes result in an error.
To avoid some confusion:
-the decoder converts from PNG to raw image
-the encoder converts from raw image to PNG
-the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image
-the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG
-when encoding, the color type in LodePNGInfo is ignored if auto_convert
is enabled, it is automatically generated instead
-when decoding, the color type in LodePNGInfo is set by the decoder to that of the original
PNG image, but it can be ignored since the raw image has the color type you requested instead
-if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion
between the color types is done if the color types are supported. If it is not
supported, an error is returned. If the types are the same, no conversion is done.
-even though some conversions aren't supported, LodePNG supports loading PNGs from any
colortype and saving PNGs to any colortype, sometimes it just requires preparing
the raw image correctly before encoding.
-both encoder and decoder use the same color converter.
The function lodepng_convert does the color conversion. It is available in the
interface but normally isn't needed since the encoder and decoder already call
it.
Non supported color conversions:
-color to grayscale when non-gray pixels are present: no error is thrown, but
the result will look ugly because only the red channel is taken (it assumes all
three channels are the same in this case so ignores green and blue). The reason
no error is given is to allow converting from three-channel grayscale images to
one-channel even if there are numerical imprecisions.
-anything to palette when the palette does not have an exact match for a from-color
in it: in this case an error is thrown
Supported color conversions:
-anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA
-any gray or gray+alpha, to gray or gray+alpha
-anything to a palette, as long as the palette has the requested colors in it
-removing alpha channel
-higher to smaller bitdepth, and vice versa
If you want no color conversion to be done (e.g. for speed or control):
-In the encoder, you can make it save a PNG with any color type by giving the
raw color mode and LodePNGInfo the same color mode, and setting auto_convert to
false.
-In the decoder, you can make it store the pixel data in the same color type
as the PNG has, by setting the color_convert setting to false. Settings in
info_raw are then ignored.
6.3. padding bits
-----------------
In the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines
have a bit amount that isn't a multiple of 8, then padding bits are used so that each
scanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output.
The raw input image you give to the encoder, and the raw output image you get from the decoder
will NOT have these padding bits, e.g. in the case of a 1-bit image with a width
of 7 pixels, the first pixel of the second scanline will the 8th bit of the first byte,
not the first bit of a new byte.
6.4. A note about 16-bits per channel and endianness
----------------------------------------------------
LodePNG uses unsigned char arrays for 16-bit per channel colors too, just like
for any other color format. The 16-bit values are stored in big endian (most
significant byte first) in these arrays. This is the opposite order of the
little endian used by x86 CPU's.
LodePNG always uses big endian because the PNG file format does so internally.
Conversions to other formats than PNG uses internally are not supported by
LodePNG on purpose, there are myriads of formats, including endianness of 16-bit
colors, the order in which you store R, G, B and A, and so on. Supporting and
converting to/from all that is outside the scope of LodePNG.
This may mean that, depending on your use case, you may want to convert the big
endian output of LodePNG to little endian with a for loop. This is certainly not
always needed, many applications and libraries support big endian 16-bit colors
anyway, but it means you cannot simply cast the unsigned char* buffer to an
unsigned short* buffer on x86 CPUs.
7. error values
---------------
All functions in LodePNG that return an error code, return 0 if everything went
OK, or a non-zero code if there was an error.
The meaning of the LodePNG error values can be retrieved with the function
lodepng_error_text: given the numerical error code, it returns a description
of the error in English as a string.
Check the implementation of lodepng_error_text to see the meaning of each code.
It is not recommended to use the numerical values to programmatically make
different decisions based on error types as the numbers are not guaranteed to
stay backwards compatible. They are for human consumption only. Programmatically
only 0 or non-0 matter.
8. chunks and PNG editing
-------------------------
If you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG
editor that should follow the rules about handling of unknown chunks, or if your
program is able to read other types of chunks than the ones handled by LodePNG,
then that's possible with the chunk functions of LodePNG.
A PNG chunk has the following layout:
4 bytes length
4 bytes type name
length bytes data
4 bytes CRC
8.1. iterating through chunks
-----------------------------
If you have a buffer containing the PNG image data, then the first chunk (the
IHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the
signature of the PNG and are not part of a chunk. But if you start at byte 8
then you have a chunk, and can check the following things of it.
NOTE: none of these functions check for memory buffer boundaries. To avoid
exploits, always make sure the buffer contains all the data of the chunks.
When using lodepng_chunk_next, make sure the returned value is within the
allocated memory.
unsigned lodepng_chunk_length(const unsigned char* chunk):
Get the length of the chunk's data. The total chunk length is this length + 12.
void lodepng_chunk_type(char type[5], const unsigned char* chunk):
unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type):
Get the type of the chunk or compare if it's a certain type
unsigned char lodepng_chunk_critical(const unsigned char* chunk):
unsigned char lodepng_chunk_private(const unsigned char* chunk):
unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk):
Check if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are).
Check if the chunk is private (public chunks are part of the standard, private ones not).
Check if the chunk is safe to copy. If it's not, then, when modifying data in a critical
chunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your
program doesn't handle that type of unknown chunk.
unsigned char* lodepng_chunk_data(unsigned char* chunk):
const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk):
Get a pointer to the start of the data of the chunk.
unsigned lodepng_chunk_check_crc(const unsigned char* chunk):
void lodepng_chunk_generate_crc(unsigned char* chunk):
Check if the crc is correct or generate a correct one.
unsigned char* lodepng_chunk_next(unsigned char* chunk):
const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk):
Iterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these
functions do no boundary checking of the allocated data whatsoever, so make sure there is enough
data available in the buffer to be able to go to the next chunk.
unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk):
unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, unsigned length,
const char* type, const unsigned char* data):
These functions are used to create new chunks that are appended to the data in *out that has
length *outsize. The append function appends an existing chunk to the new data. The create
function creates a new chunk with the given parameters and appends it. Type is the 4-letter
name of the chunk.
8.2. chunks in info_png
-----------------------
The LodePNGInfo struct contains fields with the unknown chunk in it. It has 3
buffers (each with size) to contain 3 types of unknown chunks:
the ones that come before the PLTE chunk, the ones that come between the PLTE
and the IDAT chunks, and the ones that come after the IDAT chunks.
It's necessary to make the distinction between these 3 cases because the PNG
standard forces to keep the ordering of unknown chunks compared to the critical
chunks, but does not force any other ordering rules.
info_png.unknown_chunks_data[0] is the chunks before PLTE
info_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT
info_png.unknown_chunks_data[2] is the chunks after IDAT
The chunks in these 3 buffers can be iterated through and read by using the same
way described in the previous subchapter.
When using the decoder to decode a PNG, you can make it store all unknown chunks
if you set the option settings.remember_unknown_chunks to 1. By default, this
option is off (0).
The encoder will always encode unknown chunks that are stored in the info_png.
If you need it to add a particular chunk that isn't known by LodePNG, you can
use lodepng_chunk_append or lodepng_chunk_create to the chunk data in
info_png.unknown_chunks_data[x].
Chunks that are known by LodePNG should not be added in that way. E.g. to make
LodePNG add a bKGD chunk, set background_defined to true and add the correct
parameters there instead.
9. compiler support
-------------------
No libraries other than the current standard C library are needed to compile
LodePNG. For the C++ version, only the standard C++ library is needed on top.
Add the files lodepng.c(pp) and lodepng.h to your project, include
lodepng.h where needed, and your program can read/write PNG files.
It is compatible with C90 and up, and C++03 and up.
If performance is important, use optimization when compiling! For both the
encoder and decoder, this makes a large difference.
Make sure that LodePNG is compiled with the same compiler of the same version
and with the same settings as the rest of the program, or the interfaces with
std::vectors and std::strings in C++ can be incompatible.
CHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets.
*) gcc and g++
LodePNG is developed in gcc so this compiler is natively supported. It gives no
warnings with compiler options "-Wall -Wextra -pedantic -ansi", with gcc and g++
version 4.7.1 on Linux, 32-bit and 64-bit.
*) Clang
Fully supported and warning-free.
*) Mingw
The Mingw compiler (a port of gcc for Windows) should be fully supported by
LodePNG.
*) Visual Studio and Visual C++ Express Edition
LodePNG should be warning-free with warning level W4. Two warnings were disabled
with pragmas though: warning 4244 about implicit conversions, and warning 4996
where it wants to use a non-standard function fopen_s instead of the standard C
fopen.
Visual Studio may want "stdafx.h" files to be included in each source file and
give an error "unexpected end of file while looking for precompiled header".
This is not standard C++ and will not be added to the stock LodePNG. You can
disable it for lodepng.cpp only by right clicking it, Properties, C/C++,
Precompiled Headers, and set it to Not Using Precompiled Headers there.
NOTE: Modern versions of VS should be fully supported, but old versions, e.g.
VS6, are not guaranteed to work.
*) Compilers on Macintosh
LodePNG has been reported to work both with gcc and LLVM for Macintosh, both for
C and C++.
*) Other Compilers
If you encounter problems on any compilers, feel free to let me know and I may
try to fix it if the compiler is modern and standards compliant.
10. examples
------------
This decoder example shows the most basic usage of LodePNG. More complex
examples can be found on the LodePNG website.
10.1. decoder C++ example
-------------------------
#include "lodepng.h"
#include <iostream>
int main(int argc, char *argv[]) {
const char* filename = argc > 1 ? argv[1] : "test.png";
//load and decode
std::vector<unsigned char> image;
unsigned width, height;
unsigned error = lodepng::decode(image, width, height, filename);
//if there's an error, display it
if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl;
//the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...
}
10.2. decoder C example
-----------------------
#include "lodepng.h"
int main(int argc, char *argv[]) {
unsigned error;
unsigned char* image;
size_t width, height;
const char* filename = argc > 1 ? argv[1] : "test.png";
error = lodepng_decode32_file(&image, &width, &height, filename);
if(error) printf("decoder error %u: %s\n", error, lodepng_error_text(error));
/ * use image here * /
free(image);
return 0;
}
11. state settings reference
----------------------------
A quick reference of some settings to set on the LodePNGState
For decoding:
state.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums
state.decoder.zlibsettings.custom_...: use custom inflate function
state.decoder.ignore_crc: ignore CRC checksums
state.decoder.ignore_critical: ignore unknown critical chunks
state.decoder.ignore_end: ignore missing IEND chunk. May fail if this corruption causes other errors
state.decoder.color_convert: convert internal PNG color to chosen one
state.decoder.read_text_chunks: whether to read in text metadata chunks
state.decoder.remember_unknown_chunks: whether to read in unknown chunks
state.info_raw.colortype: desired color type for decoded image
state.info_raw.bitdepth: desired bit depth for decoded image
state.info_raw....: more color settings, see struct LodePNGColorMode
state.info_png....: no settings for decoder but output, see struct LodePNGInfo
For encoding:
state.encoder.zlibsettings.btype: disable compression by setting it to 0
state.encoder.zlibsettings.use_lz77: use LZ77 in compression
state.encoder.zlibsettings.windowsize: tweak LZ77 windowsize
state.encoder.zlibsettings.minmatch: tweak min LZ77 length to match
state.encoder.zlibsettings.nicematch: tweak LZ77 match where to stop searching
state.encoder.zlibsettings.lazymatching: try one more LZ77 matching
state.encoder.zlibsettings.custom_...: use custom deflate function
state.encoder.auto_convert: choose optimal PNG color type, if 0 uses info_png
state.encoder.filter_palette_zero: PNG filter strategy for palette
state.encoder.filter_strategy: PNG filter strategy to encode with
state.encoder.force_palette: add palette even if not encoding to one
state.encoder.add_id: add LodePNG identifier and version as a text chunk
state.encoder.text_compression: use compressed text chunks for metadata
state.info_raw.colortype: color type of raw input image you provide
state.info_raw.bitdepth: bit depth of raw input image you provide
state.info_raw: more color settings, see struct LodePNGColorMode
state.info_png.color.colortype: desired color type if auto_convert is false
state.info_png.color.bitdepth: desired bit depth if auto_convert is false
state.info_png.color....: more color settings, see struct LodePNGColorMode
state.info_png....: more PNG related settings, see struct LodePNGInfo
12. changes
-----------
The version number of LodePNG is the date of the change given in the format
yyyymmdd.
Some changes aren't backwards compatible. Those are indicated with a (!)
symbol.
Not all changes are listed here, the commit history in github lists more:
https://github.com/lvandeve/lodepng
*) 17 okt 2020: prevent decoding too large text/icc chunks by default.
*) 06 mar 2020: simplified some of the dynamic memory allocations.
*) 12 jan 2020: (!) added 'end' argument to lodepng_chunk_next to allow correct
overflow checks.
*) 14 aug 2019: around 25% faster decoding thanks to huffman lookup tables.
*) 15 jun 2019: (!) auto_choose_color API changed (for bugfix: don't use palette
if gray ICC profile) and non-ICC LodePNGColorProfile renamed to
LodePNGColorStats.
*) 30 dec 2018: code style changes only: removed newlines before opening braces.
*) 10 sep 2018: added way to inspect metadata chunks without full decoding.
*) 19 aug 2018: (!) fixed color mode bKGD is encoded with and made it use
palette index in case of palette.
*) 10 aug 2018: (!) added support for gAMA, cHRM, sRGB and iCCP chunks. This
change is backwards compatible unless you relied on unknown_chunks for those.
*) 11 jun 2018: less restrictive check for pixel size integer overflow
*) 14 jan 2018: allow optionally ignoring a few more recoverable errors
*) 17 sep 2017: fix memory leak for some encoder input error cases
*) 27 nov 2016: grey+alpha auto color model detection bugfix
*) 18 apr 2016: Changed qsort to custom stable sort (for platforms w/o qsort).
*) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within
the limits of pure C90).
*) 08 dec 2015: Made load_file function return error if file can't be opened.
*) 24 okt 2015: Bugfix with decoding to palette output.
*) 18 apr 2015: Boundary PM instead of just package-merge for faster encoding.
*) 24 aug 2014: Moved to github
*) 23 aug 2014: Reduced needless memory usage of decoder.
*) 28 jun 2014: Removed fix_png setting, always support palette OOB for
simplicity. Made ColorProfile public.
*) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization.
*) 22 dec 2013: Power of two windowsize required for optimization.
*) 15 apr 2013: Fixed bug with LAC_ALPHA and color key.
*) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png).
*) 11 mar 2013: (!) Bugfix with custom free. Changed from "my" to "lodepng_"
prefix for the custom allocators and made it possible with a new #define to
use custom ones in your project without needing to change lodepng's code.
*) 28 jan 2013: Bugfix with color key.
*) 27 okt 2012: Tweaks in text chunk keyword length error handling.
*) 8 okt 2012: (!) Added new filter strategy (entropy) and new auto color mode.
(no palette). Better deflate tree encoding. New compression tweak settings.
Faster color conversions while decoding. Some internal cleanups.
*) 23 sep 2012: Reduced warnings in Visual Studio a little bit.
*) 1 sep 2012: (!) Removed #define's for giving custom (de)compression functions
and made it work with function pointers instead.
*) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc
and free functions and toggle #defines from compiler flags. Small fixes.
*) 6 may 2012: (!) Made plugging in custom zlib/deflate functions more flexible.
*) 22 apr 2012: (!) Made interface more consistent, renaming a lot. Removed
redundant C++ codec classes. Reduced amount of structs. Everything changed,
but it is cleaner now imho and functionality remains the same. Also fixed
several bugs and shrunk the implementation code. Made new samples.
*) 6 nov 2011: (!) By default, the encoder now automatically chooses the best
PNG color model and bit depth, based on the amount and type of colors of the
raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color.
*) 9 okt 2011: simpler hash chain implementation for the encoder.
*) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching.
*) 23 aug 2011: tweaked the zlib compression parameters after benchmarking.
A bug with the PNG filtertype heuristic was fixed, so that it chooses much
better ones (it's quite significant). A setting to do an experimental, slow,
brute force search for PNG filter types is added.
*) 17 aug 2011: (!) changed some C zlib related function names.
*) 16 aug 2011: made the code less wide (max 120 characters per line).
*) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors.
*) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled.
*) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman
to optimize long sequences of zeros.
*) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and
LodePNG_InfoColor_canHaveAlpha functions for convenience.
*) 7 nov 2010: added LodePNG_error_text function to get error code description.
*) 30 okt 2010: made decoding slightly faster
*) 26 okt 2010: (!) changed some C function and struct names (more consistent).
Reorganized the documentation and the declaration order in the header.
*) 08 aug 2010: only changed some comments and external samples.
*) 05 jul 2010: fixed bug thanks to warnings in the new gcc version.
*) 14 mar 2010: fixed bug where too much memory was allocated for char buffers.
*) 02 sep 2008: fixed bug where it could create empty tree that linux apps could
read by ignoring the problem but windows apps couldn't.
*) 06 jun 2008: added more error checks for out of memory cases.
*) 26 apr 2008: added a few more checks here and there to ensure more safety.
*) 06 mar 2008: crash with encoding of strings fixed
*) 02 feb 2008: support for international text chunks added (iTXt)
*) 23 jan 2008: small cleanups, and #defines to divide code in sections
*) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor.
*) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder.
*) 17 jan 2008: ability to encode and decode compressed zTXt chunks added
Also various fixes, such as in the deflate and the padding bits code.
*) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved
filtering code of encoder.
*) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A
C++ wrapper around this provides an interface almost identical to before.
Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code
are together in these files but it works both for C and C++ compilers.
*) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks
*) 30 aug 2007: bug fixed which makes this Borland C++ compatible
*) 09 aug 2007: some VS2005 warnings removed again
*) 21 jul 2007: deflate code placed in new namespace separate from zlib code
*) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images
*) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing
invalid std::vector element [0] fixed, and level 3 and 4 warnings removed
*) 02 jun 2007: made the encoder add a tag with version by default
*) 27 may 2007: zlib and png code separated (but still in the same file),
simple encoder/decoder functions added for more simple usage cases
*) 19 may 2007: minor fixes, some code cleaning, new error added (error 69),
moved some examples from here to lodepng_examples.cpp
*) 12 may 2007: palette decoding bug fixed
*) 24 apr 2007: changed the license from BSD to the zlib license
*) 11 mar 2007: very simple addition: ability to encode bKGD chunks.
*) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding
palettized PNG images. Plus little interface change with palette and texts.
*) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes.
Fixed a bug where the end code of a block had length 0 in the Huffman tree.
*) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented
and supported by the encoder, resulting in smaller PNGs at the output.
*) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone.
*) 24 jan 2007: gave encoder an error interface. Added color conversion from any
greyscale type to 8-bit greyscale with or without alpha.
*) 21 jan 2007: (!) Totally changed the interface. It allows more color types
to convert to and is more uniform. See the manual for how it works now.
*) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days:
encode/decode custom tEXt chunks, separate classes for zlib & deflate, and
at last made the decoder give errors for incorrect Adler32 or Crc.
*) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel.
*) 29 dec 2006: Added support for encoding images without alpha channel, and
cleaned out code as well as making certain parts faster.
*) 28 dec 2006: Added "Settings" to the encoder.
*) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now.
Removed some code duplication in the decoder. Fixed little bug in an example.
*) 09 dec 2006: (!) Placed output parameters of public functions as first parameter.
Fixed a bug of the decoder with 16-bit per color.
*) 15 okt 2006: Changed documentation structure
*) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the
given image buffer, however for now it's not compressed.
*) 08 sep 2006: (!) Changed to interface with a Decoder class
*) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different
way. Renamed decodePNG to decodePNGGeneric.
*) 29 jul 2006: (!) Changed the interface: image info is now returned as a
struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy.
*) 28 jul 2006: Cleaned the code and added new error checks.
Corrected terminology "deflate" into "inflate".
*) 23 jun 2006: Added SDL example in the documentation in the header, this
example allows easy debugging by displaying the PNG and its transparency.
*) 22 jun 2006: (!) Changed way to obtain error value. Added
loadFile function for convenience. Made decodePNG32 faster.
*) 21 jun 2006: (!) Changed type of info vector to unsigned.
Changed position of palette in info vector. Fixed an important bug that
happened on PNGs with an uncompressed block.
*) 16 jun 2006: Internally changed unsigned into unsigned where
needed, and performed some optimizations.
*) 07 jun 2006: (!) Renamed functions to decodePNG and placed them
in LodePNG namespace. Changed the order of the parameters. Rewrote the
documentation in the header. Renamed files to lodepng.cpp and lodepng.h
*) 22 apr 2006: Optimized and improved some code
*) 07 sep 2005: (!) Changed to std::vector interface
*) 12 aug 2005: Initial release (C++, decoder only)
13. contact information
-----------------------
Feel free to contact me with suggestions, problems, comments, ... concerning
LodePNG. If you encounter a PNG image that doesn't work properly with this
decoder, feel free to send it and I'll use it to find and fix the problem.
My email address is (puzzle the account and domain together with an @ symbol):
Domain: gmail dot com.
Account: lode dot vandevenne.
Copyright (c) 2005-2020 Lode Vandevenne
*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/lodepng/lv_lodepng.h | /**
* @file lv_lodepng.h
*
*/
#ifndef LV_LODEPNG_H
#define LV_LODEPNG_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../lv_conf_internal.h"
#if LV_USE_LODEPNG
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Register the PNG decoder functions in LVGL
*/
void lv_lodepng_init(void);
void lv_lodepng_deinit(void);
/**********************
* MACROS
**********************/
#endif /*LV_USE_LODEPNG*/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*LV_LODEPNG_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/lodepng/lodepng.c | /*
LodePNG version 20201017
Copyright (c) 2005-2020 Lode Vandevenne
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
/*
The manual and changelog are in the header file "lodepng.h"
Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C.
*/
#include "lodepng.h"
#if LV_USE_LODEPNG
#ifdef LODEPNG_COMPILE_DISK
#include <limits.h> /* LONG_MAX */
#endif /* LODEPNG_COMPILE_DISK */
#ifdef LODEPNG_COMPILE_ALLOCATORS
#include <stdlib.h> /* allocations */
#endif /* LODEPNG_COMPILE_ALLOCATORS */
#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/
#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/
#pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/
#endif /*_MSC_VER */
const char * LODEPNG_VERSION_STRING = "20201017";
/*
This source file is built up in the following large parts. The code sections
with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way.
-Tools for C and common code for PNG and Zlib
-C Code for Zlib (huffman, deflate, ...)
-C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...)
-The C++ wrapper around all of the above
*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // Tools for C, and common code for PNG and Zlib. // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/*The malloc, realloc and free functions defined here with "lodepng_" in front
of the name, so that you can easily change them to others related to your
platform if needed. Everything else in the code calls these. Pass
-DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out
#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and
define them in your own project's source files without needing to change
lodepng source code. Don't forget to remove "static" if you copypaste them
from here.*/
#ifdef LODEPNG_COMPILE_ALLOCATORS
static void * lodepng_malloc(size_t size)
{
#ifdef LODEPNG_MAX_ALLOC
if(size > LODEPNG_MAX_ALLOC) return 0;
#endif
return lv_malloc(size);
}
/* NOTE: when realloc returns NULL, it leaves the original memory untouched */
static void * lodepng_realloc(void * ptr, size_t new_size)
{
#ifdef LODEPNG_MAX_ALLOC
if(new_size > LODEPNG_MAX_ALLOC) return 0;
#endif
return lv_realloc(ptr, new_size);
}
static void lodepng_free(void * ptr)
{
lv_free(ptr);
}
#else /*LODEPNG_COMPILE_ALLOCATORS*/
/* TODO: support giving additional void* payload to the custom allocators */
void * lodepng_malloc(size_t size);
void * lodepng_realloc(void * ptr, size_t new_size);
void lodepng_free(void * ptr);
#endif /*LODEPNG_COMPILE_ALLOCATORS*/
/* convince the compiler to inline a function, for use when this measurably improves performance */
/* inline is not available in C90, but use it when supported by the compiler */
#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || (defined(__cplusplus) && (__cplusplus >= 199711L))
#define LODEPNG_INLINE inline
#else
#define LODEPNG_INLINE /* not available */
#endif
/* restrict is not available in C90, but use it when supported by the compiler */
#if (defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))) ||\
(defined(_MSC_VER) && (_MSC_VER >= 1400)) || \
(defined(__WATCOMC__) && (__WATCOMC__ >= 1250) && !defined(__cplusplus))
#define LODEPNG_RESTRICT __restrict
#else
#define LODEPNG_RESTRICT /* not available */
#endif
/* Replacements for C library functions such as memcpy and strlen, to support platforms
where a full C library is not available. The compiler can recognize them and compile
to something as fast. */
static void lodepng_memcpy(void * LODEPNG_RESTRICT dst,
const void * LODEPNG_RESTRICT src, size_t size)
{
lv_memcpy(dst, src, size);
}
static void lodepng_memset(void * LODEPNG_RESTRICT dst,
int value, size_t num)
{
lv_memset(dst, value, num);
}
/* does not check memory out of bounds, do not use on untrusted data */
static size_t lodepng_strlen(const char * a)
{
const char * orig = a;
/* avoid warning about unused function in case of disabled COMPILE... macros */
(void)(&lodepng_strlen);
while(*a) a++;
return (size_t)(a - orig);
}
#define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b))
#define LODEPNG_MIN(a, b) (((a) < (b)) ? (a) : (b))
#define LODEPNG_ABS(x) ((x) < 0 ? -(x) : (x))
#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_DECODER)
/* Safely check if adding two integers will overflow (no undefined
behavior, compiler removing the code, etc...) and output result. */
static int lodepng_addofl(size_t a, size_t b, size_t * result)
{
*result = a + b; /* Unsigned addition is well defined and safe in C90 */
return *result < a;
}
#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_DECODER)*/
#ifdef LODEPNG_COMPILE_DECODER
/* Safely check if multiplying two integers will overflow (no undefined
behavior, compiler removing the code, etc...) and output result. */
static int lodepng_mulofl(size_t a, size_t b, size_t * result)
{
*result = a * b; /* Unsigned multiplication is well defined and safe in C90 */
return (a != 0 && *result / a != b);
}
#ifdef LODEPNG_COMPILE_ZLIB
/* Safely check if a + b > c, even if overflow could happen. */
static int lodepng_gtofl(size_t a, size_t b, size_t c)
{
size_t d;
if(lodepng_addofl(a, b, &d)) return 1;
return d > c;
}
#endif /*LODEPNG_COMPILE_ZLIB*/
#endif /*LODEPNG_COMPILE_DECODER*/
/*
Often in case of an error a value is assigned to a variable and then it breaks
out of a loop (to go to the cleanup phase of a function). This macro does that.
It makes the error handling code shorter and more readable.
Example: if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83);
*/
#define CERROR_BREAK(errorvar, code){\
errorvar = code;\
break;\
}
/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
#define ERROR_BREAK(code) CERROR_BREAK(error, code)
/*Set error var to the error code, and return it.*/
#define CERROR_RETURN_ERROR(errorvar, code){\
errorvar = code;\
return code;\
}
/*Try the code, if it returns error, also return the error.*/
#define CERROR_TRY_RETURN(call){\
unsigned error = call;\
if(error) return error;\
}
/*Set error var to the error code, and return from the void function.*/
#define CERROR_RETURN(errorvar, code){\
errorvar = code;\
return;\
}
/*
About uivector, ucvector and string:
-All of them wrap dynamic arrays or text strings in a similar way.
-LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
-The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
-They're not used in the interface, only internally in this file as static functions.
-As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
*/
#ifdef LODEPNG_COMPILE_ZLIB
#ifdef LODEPNG_COMPILE_ENCODER
/*dynamic vector of unsigned ints*/
typedef struct uivector {
unsigned * data;
size_t size; /*size in number of unsigned longs*/
size_t allocsize; /*allocated size in bytes*/
} uivector;
static void uivector_cleanup(void * p)
{
((uivector *)p)->size = ((uivector *)p)->allocsize = 0;
lodepng_free(((uivector *)p)->data);
((uivector *)p)->data = NULL;
}
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned uivector_resize(uivector * p, size_t size)
{
size_t allocsize = size * sizeof(unsigned);
if(allocsize > p->allocsize) {
size_t newsize = allocsize + (p->allocsize >> 1u);
void * data = lodepng_realloc(p->data, newsize);
if(data) {
p->allocsize = newsize;
p->data = (unsigned *)data;
}
else return 0; /*error: not enough memory*/
}
p->size = size;
return 1; /*success*/
}
static void uivector_init(uivector * p)
{
p->data = NULL;
p->size = p->allocsize = 0;
}
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned uivector_push_back(uivector * p, unsigned c)
{
if(!uivector_resize(p, p->size + 1)) return 0;
p->data[p->size - 1] = c;
return 1;
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_ZLIB*/
/* /////////////////////////////////////////////////////////////////////////// */
/*dynamic vector of unsigned chars*/
typedef struct ucvector {
unsigned char * data;
size_t size; /*used size*/
size_t allocsize; /*allocated size*/
} ucvector;
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned ucvector_resize(ucvector * p, size_t size)
{
if(size > p->allocsize) {
size_t newsize = size + (p->allocsize >> 1u);
void * data = lodepng_realloc(p->data, newsize);
if(data) {
p->allocsize = newsize;
p->data = (unsigned char *)data;
}
else return 0; /*error: not enough memory*/
}
p->size = size;
return 1; /*success*/
}
static ucvector ucvector_init(unsigned char * buffer, size_t size)
{
ucvector v;
v.data = buffer;
v.allocsize = v.size = size;
return v;
}
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_PNG
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*free string pointer and set it to NULL*/
static void string_cleanup(char ** out)
{
lodepng_free(*out);
*out = NULL;
}
/*also appends null termination character*/
static char * alloc_string_sized(const char * in, size_t insize)
{
char * out = (char *)lodepng_malloc(insize + 1);
if(out) {
lodepng_memcpy(out, in, insize);
out[insize] = 0;
}
return out;
}
/* dynamically allocates a new string with a copy of the null terminated input text */
static char * alloc_string(const char * in)
{
return alloc_string_sized(in, lodepng_strlen(in));
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
#endif /*LODEPNG_COMPILE_PNG*/
/* ////////////////////////////////////////////////////////////////////////// */
#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG)
static unsigned lodepng_read32bitInt(const unsigned char * buffer)
{
return (((unsigned)buffer[0] << 24u) | ((unsigned)buffer[1] << 16u) |
((unsigned)buffer[2] << 8u) | (unsigned)buffer[3]);
}
#endif /*defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG)*/
#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)
/*buffer must have at least 4 allocated bytes available*/
static void lodepng_set32bitInt(unsigned char * buffer, unsigned value)
{
buffer[0] = (unsigned char)((value >> 24) & 0xff);
buffer[1] = (unsigned char)((value >> 16) & 0xff);
buffer[2] = (unsigned char)((value >> 8) & 0xff);
buffer[3] = (unsigned char)((value) & 0xff);
}
#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
/* ////////////////////////////////////////////////////////////////////////// */
/* / File IO / */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_DISK
/* returns negative value on error. This should be pure C compatible, so no fstat. */
static long lodepng_filesize(const char * filename)
{
lv_fs_file_t f;
lv_fs_res_t res = lv_fs_open(&f, filename, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) return -1;
uint32_t size = 0;
if(lv_fs_seek(&f, 0, LV_FS_SEEK_END) != 0) {
lv_fs_close(&f);
return -1;
}
lv_fs_tell(&f, &size);
lv_fs_close(&f);
return size;
}
/* load file into buffer that already has the correct allocated size. Returns error code.*/
static unsigned lodepng_buffer_file(unsigned char * out, size_t size, const char * filename)
{
lv_fs_file_t f;
lv_fs_res_t res = lv_fs_open(&f, filename, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) return 78;
uint32_t br;
res = lv_fs_read(&f, out, size, &br);
lv_fs_close(&f);
if(res != LV_FS_RES_OK) return 78;
if(br != size) return 78;
return 0;
}
unsigned lodepng_load_file(unsigned char ** out, size_t * outsize, const char * filename)
{
long size = lodepng_filesize(filename);
if(size < 0) return 78;
*outsize = (size_t)size;
*out = (unsigned char *)lodepng_malloc((size_t)size);
if(!(*out) && size > 0) return 83; /*the above malloc failed*/
return lodepng_buffer_file(*out, (size_t)size, filename);
}
/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
unsigned lodepng_save_file(const unsigned char * buffer, size_t buffersize, const char * filename)
{
lv_fs_file_t f;
lv_fs_res_t res = lv_fs_open(&f, filename, LV_FS_MODE_WR);
if(res != LV_FS_RES_OK) return 79;
uint32_t bw;
res = lv_fs_write(&f, buffer, buffersize, &bw);
lv_fs_close(&f);
return 0;
}
#endif /*LODEPNG_COMPILE_DISK*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // End of common code and tools. Begin of Zlib related code. // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_ZLIB
#ifdef LODEPNG_COMPILE_ENCODER
typedef struct {
ucvector * data;
unsigned char bp; /*ok to overflow, indicates bit pos inside byte*/
} LodePNGBitWriter;
static void LodePNGBitWriter_init(LodePNGBitWriter * writer, ucvector * data)
{
writer->data = data;
writer->bp = 0;
}
/*TODO: this ignores potential out of memory errors*/
#define WRITEBIT(writer, bit){\
/* append new byte */\
if(((writer->bp) & 7u) == 0) {\
if(!ucvector_resize(writer->data, writer->data->size + 1)) return;\
writer->data->data[writer->data->size - 1] = 0;\
}\
(writer->data->data[writer->data->size - 1]) |= (bit << ((writer->bp) & 7u));\
++writer->bp;\
}
/* LSB of value is written first, and LSB of bytes is used first */
static void writeBits(LodePNGBitWriter * writer, unsigned value, size_t nbits)
{
if(nbits == 1) { /* compiler should statically compile this case if nbits == 1 */
WRITEBIT(writer, value);
}
else {
/* TODO: increase output size only once here rather than in each WRITEBIT */
size_t i;
for(i = 0; i != nbits; ++i) {
WRITEBIT(writer, (unsigned char)((value >> i) & 1));
}
}
}
/* This one is to use for adding huffman symbol, the value bits are written MSB first */
static void writeBitsReversed(LodePNGBitWriter * writer, unsigned value, size_t nbits)
{
size_t i;
for(i = 0; i != nbits; ++i) {
/* TODO: increase output size only once here rather than in each WRITEBIT */
WRITEBIT(writer, (unsigned char)((value >> (nbits - 1u - i)) & 1u));
}
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_DECODER
typedef struct {
const unsigned char * data;
size_t size; /*size of data in bytes*/
size_t bitsize; /*size of data in bits, end of valid bp values, should be 8*size*/
size_t bp;
unsigned buffer; /*buffer for reading bits. NOTE: 'unsigned' must support at least 32 bits*/
} LodePNGBitReader;
/* data size argument is in bytes. Returns error if size too large causing overflow */
static unsigned LodePNGBitReader_init(LodePNGBitReader * reader, const unsigned char * data, size_t size)
{
size_t temp;
reader->data = data;
reader->size = size;
/* size in bits, return error if overflow (if size_t is 32 bit this supports up to 500MB) */
if(lodepng_mulofl(size, 8u, &reader->bitsize)) return 105;
/*ensure incremented bp can be compared to bitsize without overflow even when it would be incremented 32 too much and
trying to ensure 32 more bits*/
if(lodepng_addofl(reader->bitsize, 64u, &temp)) return 105;
reader->bp = 0;
reader->buffer = 0;
return 0; /*ok*/
}
/*
ensureBits functions:
Ensures the reader can at least read nbits bits in one or more readBits calls,
safely even if not enough bits are available.
Returns 1 if there are enough bits available, 0 if not.
*/
/*See ensureBits documentation above. This one ensures exactly 1 bit */
/*static unsigned ensureBits1(LodePNGBitReader* reader) {
if(reader->bp >= reader->bitsize) return 0;
reader->buffer = (unsigned)reader->data[reader->bp >> 3u] >> (reader->bp & 7u);
return 1;
}*/
/*See ensureBits documentation above. This one ensures up to 9 bits */
static unsigned ensureBits9(LodePNGBitReader * reader, size_t nbits)
{
size_t start = reader->bp >> 3u;
size_t size = reader->size;
if(start + 1u < size) {
reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u);
reader->buffer >>= (reader->bp & 7u);
return 1;
}
else {
reader->buffer = 0;
if(start + 0u < size) reader->buffer |= reader->data[start + 0];
reader->buffer >>= (reader->bp & 7u);
return reader->bp + nbits <= reader->bitsize;
}
}
/*See ensureBits documentation above. This one ensures up to 17 bits */
static unsigned ensureBits17(LodePNGBitReader * reader, size_t nbits)
{
size_t start = reader->bp >> 3u;
size_t size = reader->size;
if(start + 2u < size) {
reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) |
((unsigned)reader->data[start + 2] << 16u);
reader->buffer >>= (reader->bp & 7u);
return 1;
}
else {
reader->buffer = 0;
if(start + 0u < size) reader->buffer |= reader->data[start + 0];
if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);
reader->buffer >>= (reader->bp & 7u);
return reader->bp + nbits <= reader->bitsize;
}
}
/*See ensureBits documentation above. This one ensures up to 25 bits */
static LODEPNG_INLINE unsigned ensureBits25(LodePNGBitReader * reader, size_t nbits)
{
size_t start = reader->bp >> 3u;
size_t size = reader->size;
if(start + 3u < size) {
reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) |
((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u);
reader->buffer >>= (reader->bp & 7u);
return 1;
}
else {
reader->buffer = 0;
if(start + 0u < size) reader->buffer |= reader->data[start + 0];
if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);
if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u);
reader->buffer >>= (reader->bp & 7u);
return reader->bp + nbits <= reader->bitsize;
}
}
/*See ensureBits documentation above. This one ensures up to 32 bits */
static LODEPNG_INLINE unsigned ensureBits32(LodePNGBitReader * reader, size_t nbits)
{
size_t start = reader->bp >> 3u;
size_t size = reader->size;
if(start + 4u < size) {
reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) |
((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u);
reader->buffer >>= (reader->bp & 7u);
reader->buffer |= (((unsigned)reader->data[start + 4] << 24u) << (8u - (reader->bp & 7u)));
return 1;
}
else {
reader->buffer = 0;
if(start + 0u < size) reader->buffer |= reader->data[start + 0];
if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);
if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u);
if(start + 3u < size) reader->buffer |= ((unsigned)reader->data[start + 3] << 24u);
reader->buffer >>= (reader->bp & 7u);
return reader->bp + nbits <= reader->bitsize;
}
}
/* Get bits without advancing the bit pointer. Must have enough bits available with ensureBits. Max nbits is 31. */
static unsigned peekBits(LodePNGBitReader * reader, size_t nbits)
{
/* The shift allows nbits to be only up to 31. */
return reader->buffer & ((1u << nbits) - 1u);
}
/* Must have enough bits available with ensureBits */
static void advanceBits(LodePNGBitReader * reader, size_t nbits)
{
reader->buffer >>= nbits;
reader->bp += nbits;
}
/* Must have enough bits available with ensureBits */
static unsigned readBits(LodePNGBitReader * reader, size_t nbits)
{
unsigned result = peekBits(reader, nbits);
advanceBits(reader, nbits);
return result;
}
#if 0 /*Disable because tests fail due to unused declaration*/
/* Public for testing only. steps and result must have numsteps values. */
static unsigned lode_png_test_bitreader(const unsigned char * data, size_t size,
size_t numsteps, const size_t * steps, unsigned * result)
{
size_t i;
LodePNGBitReader reader;
unsigned error = LodePNGBitReader_init(&reader, data, size);
if(error) return 0;
for(i = 0; i < numsteps; i++) {
size_t step = steps[i];
unsigned ok;
if(step > 25) ok = ensureBits32(&reader, step);
else if(step > 17) ok = ensureBits25(&reader, step);
else if(step > 9) ok = ensureBits17(&reader, step);
else ok = ensureBits9(&reader, step);
if(!ok) return 0;
result[i] = readBits(&reader, step);
}
return 1;
}
#endif
#endif /*LODEPNG_COMPILE_DECODER*/
static unsigned reverseBits(unsigned bits, unsigned num)
{
/*TODO: implement faster lookup table based version when needed*/
unsigned i, result = 0;
for(i = 0; i < num; i++) result |= ((bits >> (num - i - 1u)) & 1u) << i;
return result;
}
/* ////////////////////////////////////////////////////////////////////////// */
/* / Deflate - Huffman / */
/* ////////////////////////////////////////////////////////////////////////// */
#define FIRST_LENGTH_CODE_INDEX 257
#define LAST_LENGTH_CODE_INDEX 285
/*256 literals, the end code, some length codes, and 2 unused codes*/
#define NUM_DEFLATE_CODE_SYMBOLS 288
/*the distance codes have their own symbols, 30 used, 2 unused*/
#define NUM_DISTANCE_SYMBOLS 32
/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
#define NUM_CODE_LENGTH_CODES 19
/*the base lengths represented by codes 257-285*/
static const unsigned LENGTHBASE[29]
= {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
67, 83, 99, 115, 131, 163, 195, 227, 258
};
/*the extra bits used by codes 257-285 (added to base length)*/
static const unsigned LENGTHEXTRA[29]
= {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
4, 4, 4, 4, 5, 5, 5, 5, 0
};
/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
static const unsigned DISTANCEBASE[30]
= {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577
};
/*the extra bits of backwards distances (added to base)*/
static const unsigned DISTANCEEXTRA[30]
= {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,
8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13
};
/*the order in which "code length alphabet code lengths" are stored as specified by deflate, out of this the huffman
tree of the dynamic huffman tree lengths is generated*/
static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]
= {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
/* ////////////////////////////////////////////////////////////////////////// */
/*
Huffman tree struct, containing multiple representations of the tree
*/
typedef struct HuffmanTree {
unsigned * codes; /*the huffman codes (bit patterns representing the symbols)*/
unsigned * lengths; /*the lengths of the huffman codes*/
unsigned maxbitlen; /*maximum number of bits a single code can get*/
unsigned numcodes; /*number of symbols in the alphabet = number of codes*/
/* for reading only */
unsigned char * table_len; /*length of symbol from lookup table, or max length if secondary lookup needed*/
unsigned short * table_value; /*value of symbol from lookup table, or pointer to secondary table if needed*/
} HuffmanTree;
static void HuffmanTree_init(HuffmanTree * tree)
{
tree->codes = 0;
tree->lengths = 0;
tree->table_len = 0;
tree->table_value = 0;
}
static void HuffmanTree_cleanup(HuffmanTree * tree)
{
lodepng_free(tree->codes);
lodepng_free(tree->lengths);
lodepng_free(tree->table_len);
lodepng_free(tree->table_value);
}
/* amount of bits for first huffman table lookup (aka root bits), see HuffmanTree_makeTable and huffmanDecodeSymbol.*/
/* values 8u and 9u work the fastest */
#define FIRSTBITS 9u
/* a symbol value too big to represent any valid symbol, to indicate reading disallowed huffman bits combination,
which is possible in case of only 0 or 1 present symbols. */
#define INVALIDSYMBOL 65535u
/* make table for huffman decoding */
static unsigned HuffmanTree_makeTable(HuffmanTree * tree)
{
static const unsigned headsize = 1u << FIRSTBITS; /*size of the first table*/
static const unsigned mask = (1u << FIRSTBITS) /*headsize*/ - 1u;
size_t i, numpresent, pointer, size; /*total table size*/
unsigned * maxlens = (unsigned *)lodepng_malloc(headsize * sizeof(unsigned));
if(!maxlens) return 83; /*alloc fail*/
/* compute maxlens: max total bit length of symbols sharing prefix in the first table*/
lodepng_memset(maxlens, 0, headsize * sizeof(*maxlens));
for(i = 0; i < tree->numcodes; i++) {
unsigned symbol = tree->codes[i];
unsigned l = tree->lengths[i];
unsigned index;
if(l <= FIRSTBITS) continue; /*symbols that fit in first table don't increase secondary table size*/
/*get the FIRSTBITS MSBs, the MSBs of the symbol are encoded first. See later comment about the reversing*/
index = reverseBits(symbol >> (l - FIRSTBITS), FIRSTBITS);
maxlens[index] = LODEPNG_MAX(maxlens[index], l);
}
/* compute total table size: size of first table plus all secondary tables for symbols longer than FIRSTBITS */
size = headsize;
for(i = 0; i < headsize; ++i) {
unsigned l = maxlens[i];
if(l > FIRSTBITS) size += (1u << (l - FIRSTBITS));
}
tree->table_len = (unsigned char *)lodepng_malloc(size * sizeof(*tree->table_len));
tree->table_value = (unsigned short *)lodepng_malloc(size * sizeof(*tree->table_value));
if(!tree->table_len || !tree->table_value) {
lodepng_free(maxlens);
/* freeing tree->table values is done at a higher scope */
return 83; /*alloc fail*/
}
/*initialize with an invalid length to indicate unused entries*/
for(i = 0; i < size; ++i) tree->table_len[i] = 16;
/*fill in the first table for long symbols: max prefix size and pointer to secondary tables*/
pointer = headsize;
for(i = 0; i < headsize; ++i) {
unsigned l = maxlens[i];
if(l <= FIRSTBITS) continue;
tree->table_len[i] = l;
tree->table_value[i] = pointer;
pointer += (1u << (l - FIRSTBITS));
}
lodepng_free(maxlens);
/*fill in the first table for short symbols, or secondary table for long symbols*/
numpresent = 0;
for(i = 0; i < tree->numcodes; ++i) {
unsigned l = tree->lengths[i];
unsigned symbol = tree->codes[i]; /*the huffman bit pattern. i itself is the value.*/
/*reverse bits, because the huffman bits are given in MSB first order but the bit reader reads LSB first*/
unsigned reverse = reverseBits(symbol, l);
if(l == 0) continue;
numpresent++;
if(l <= FIRSTBITS) {
/*short symbol, fully in first table, replicated num times if l < FIRSTBITS*/
unsigned num = 1u << (FIRSTBITS - l);
unsigned j;
for(j = 0; j < num; ++j) {
/*bit reader will read the l bits of symbol first, the remaining FIRSTBITS - l bits go to the MSB's*/
unsigned index = reverse | (j << l);
if(tree->table_len[index] != 16) return 55; /*invalid tree: long symbol shares prefix with short symbol*/
tree->table_len[index] = l;
tree->table_value[index] = i;
}
}
else {
/*long symbol, shares prefix with other long symbols in first lookup table, needs second lookup*/
/*the FIRSTBITS MSBs of the symbol are the first table index*/
unsigned index = reverse & mask;
unsigned maxlen = tree->table_len[index];
/*log2 of secondary table length, should be >= l - FIRSTBITS*/
unsigned tablelen = maxlen - FIRSTBITS;
unsigned start = tree->table_value[index]; /*starting index in secondary table*/
unsigned num = 1u << (tablelen - (l - FIRSTBITS)); /*amount of entries of this symbol in secondary table*/
unsigned j;
if(maxlen < l) return 55; /*invalid tree: long symbol shares prefix with short symbol*/
for(j = 0; j < num; ++j) {
unsigned reverse2 = reverse >> FIRSTBITS; /* l - FIRSTBITS bits */
unsigned index2 = start + (reverse2 | (j << (l - FIRSTBITS)));
tree->table_len[index2] = l;
tree->table_value[index2] = i;
}
}
}
if(numpresent < 2) {
/* In case of exactly 1 symbol, in theory the huffman symbol needs 0 bits,
but deflate uses 1 bit instead. In case of 0 symbols, no symbols can
appear at all, but such huffman tree could still exist (e.g. if distance
codes are never used). In both cases, not all symbols of the table will be
filled in. Fill them in with an invalid symbol value so returning them from
huffmanDecodeSymbol will cause error. */
for(i = 0; i < size; ++i) {
if(tree->table_len[i] == 16) {
/* As length, use a value smaller than FIRSTBITS for the head table,
and a value larger than FIRSTBITS for the secondary table, to ensure
valid behavior for advanceBits when reading this symbol. */
tree->table_len[i] = (i < headsize) ? 1 : (FIRSTBITS + 1);
tree->table_value[i] = INVALIDSYMBOL;
}
}
}
else {
/* A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
If that is not the case (due to too long length codes), the table will not
have been fully used, and this is an error (not all bit combinations can be
decoded): an oversubscribed huffman tree, indicated by error 55. */
for(i = 0; i < size; ++i) {
if(tree->table_len[i] == 16) return 55;
}
}
return 0;
}
/*
Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
numcodes, lengths and maxbitlen must already be filled in correctly. return
value is error.
*/
static unsigned HuffmanTree_makeFromLengths2(HuffmanTree * tree)
{
unsigned * blcount;
unsigned * nextcode;
unsigned error = 0;
unsigned bits, n;
tree->codes = (unsigned *)lodepng_malloc(tree->numcodes * sizeof(unsigned));
blcount = (unsigned *)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned));
nextcode = (unsigned *)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned));
if(!tree->codes || !blcount || !nextcode) error = 83; /*alloc fail*/
if(!error) {
for(n = 0; n != tree->maxbitlen + 1; n++) blcount[n] = nextcode[n] = 0;
/*step 1: count number of instances of each code length*/
for(bits = 0; bits != tree->numcodes; ++bits) ++blcount[tree->lengths[bits]];
/*step 2: generate the nextcode values*/
for(bits = 1; bits <= tree->maxbitlen; ++bits) {
nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1u;
}
/*step 3: generate all the codes*/
for(n = 0; n != tree->numcodes; ++n) {
if(tree->lengths[n] != 0) {
tree->codes[n] = nextcode[tree->lengths[n]]++;
/*remove superfluous bits from the code*/
tree->codes[n] &= ((1u << tree->lengths[n]) - 1u);
}
}
}
lodepng_free(blcount);
lodepng_free(nextcode);
if(!error) error = HuffmanTree_makeTable(tree);
return error;
}
/*
given the code lengths (as stored in the PNG file), generate the tree as defined
by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
return value is error.
*/
static unsigned HuffmanTree_makeFromLengths(HuffmanTree * tree, const unsigned * bitlen,
size_t numcodes, unsigned maxbitlen)
{
unsigned i;
tree->lengths = (unsigned *)lodepng_malloc(numcodes * sizeof(unsigned));
if(!tree->lengths) return 83; /*alloc fail*/
for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i];
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
tree->maxbitlen = maxbitlen;
return HuffmanTree_makeFromLengths2(tree);
}
#ifdef LODEPNG_COMPILE_ENCODER
/*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding",
Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/
/*chain node for boundary package merge*/
typedef struct BPMNode {
int weight; /*the sum of all weights in this chain*/
unsigned index; /*index of this leaf node (called "count" in the paper)*/
struct BPMNode * tail; /*the next nodes in this chain (null if last)*/
int in_use;
} BPMNode;
/*lists of chains*/
typedef struct BPMLists {
/*memory pool*/
unsigned memsize;
BPMNode * memory;
unsigned numfree;
unsigned nextfree;
BPMNode ** freelist;
/*two heads of lookahead chains per list*/
unsigned listsize;
BPMNode ** chains0;
BPMNode ** chains1;
} BPMLists;
/*creates a new chain node with the given parameters, from the memory in the lists */
static BPMNode * bpmnode_create(BPMLists * lists, int weight, unsigned index, BPMNode * tail)
{
unsigned i;
BPMNode * result;
/*memory full, so garbage collect*/
if(lists->nextfree >= lists->numfree) {
/*mark only those that are in use*/
for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0;
for(i = 0; i != lists->listsize; ++i) {
BPMNode * node;
for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1;
for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1;
}
/*collect those that are free*/
lists->numfree = 0;
for(i = 0; i != lists->memsize; ++i) {
if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i];
}
lists->nextfree = 0;
}
result = lists->freelist[lists->nextfree++];
result->weight = weight;
result->index = index;
result->tail = tail;
return result;
}
/*sort the leaves with stable mergesort*/
static void bpmnode_sort(BPMNode * leaves, size_t num)
{
BPMNode * mem = (BPMNode *)lodepng_malloc(sizeof(*leaves) * num);
size_t width, counter = 0;
for(width = 1; width < num; width *= 2) {
BPMNode * a = (counter & 1) ? mem : leaves;
BPMNode * b = (counter & 1) ? leaves : mem;
size_t p;
for(p = 0; p < num; p += 2 * width) {
size_t q = (p + width > num) ? num : (p + width);
size_t r = (p + 2 * width > num) ? num : (p + 2 * width);
size_t i = p, j = q, k;
for(k = p; k < r; k++) {
if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++];
else b[k] = a[j++];
}
}
counter++;
}
if(counter & 1) lodepng_memcpy(leaves, mem, sizeof(*leaves) * num);
lodepng_free(mem);
}
/*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/
static void boundaryPM(BPMLists * lists, BPMNode * leaves, size_t numpresent, int c, int num)
{
unsigned lastindex = lists->chains1[c]->index;
if(c == 0) {
if(lastindex >= numpresent) return;
lists->chains0[c] = lists->chains1[c];
lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0);
}
else {
/*sum of the weights of the head nodes of the previous lookahead chains.*/
int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight;
lists->chains0[c] = lists->chains1[c];
if(lastindex < numpresent && sum > leaves[lastindex].weight) {
lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail);
return;
}
lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]);
/*in the end we are only interested in the chain of the last list, so no
need to recurse if we're at the last one (this gives measurable speedup)*/
if(num + 1 < (int)(2 * numpresent - 2)) {
boundaryPM(lists, leaves, numpresent, c - 1, num);
boundaryPM(lists, leaves, numpresent, c - 1, num);
}
}
}
unsigned lodepng_huffman_code_lengths(unsigned * lengths, const unsigned * frequencies,
size_t numcodes, unsigned maxbitlen)
{
unsigned error = 0;
unsigned i;
size_t numpresent = 0; /*number of symbols with non-zero frequency*/
BPMNode * leaves; /*the symbols, only those with > 0 frequency*/
if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
if((1u << maxbitlen) < (unsigned)numcodes) return 80; /*error: represent all symbols*/
leaves = (BPMNode *)lodepng_malloc(numcodes * sizeof(*leaves));
if(!leaves) return 83; /*alloc fail*/
for(i = 0; i != numcodes; ++i) {
if(frequencies[i] > 0) {
leaves[numpresent].weight = (int)frequencies[i];
leaves[numpresent].index = i;
++numpresent;
}
}
lodepng_memset(lengths, 0, numcodes * sizeof(*lengths));
/*ensure at least two present symbols. There should be at least one symbol
according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To
make these work as well ensure there are at least two symbols. The
Package-Merge code below also doesn't work correctly if there's only one
symbol, it'd give it the theoretical 0 bits but in practice zlib wants 1 bit*/
if(numpresent == 0) {
lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/
}
else if(numpresent == 1) {
lengths[leaves[0].index] = 1;
lengths[leaves[0].index == 0 ? 1 : 0] = 1;
}
else {
BPMLists lists;
BPMNode * node;
bpmnode_sort(leaves, numpresent);
lists.listsize = maxbitlen;
lists.memsize = 2 * maxbitlen * (maxbitlen + 1);
lists.nextfree = 0;
lists.numfree = lists.memsize;
lists.memory = (BPMNode *)lodepng_malloc(lists.memsize * sizeof(*lists.memory));
lists.freelist = (BPMNode **)lodepng_malloc(lists.memsize * sizeof(BPMNode *));
lists.chains0 = (BPMNode **)lodepng_malloc(lists.listsize * sizeof(BPMNode *));
lists.chains1 = (BPMNode **)lodepng_malloc(lists.listsize * sizeof(BPMNode *));
if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/
if(!error) {
for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i];
bpmnode_create(&lists, leaves[0].weight, 1, 0);
bpmnode_create(&lists, leaves[1].weight, 2, 0);
for(i = 0; i != lists.listsize; ++i) {
lists.chains0[i] = &lists.memory[0];
lists.chains1[i] = &lists.memory[1];
}
/*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/
for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i);
for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) {
for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index];
}
}
lodepng_free(lists.memory);
lodepng_free(lists.freelist);
lodepng_free(lists.chains0);
lodepng_free(lists.chains1);
}
lodepng_free(leaves);
return error;
}
/*Create the Huffman tree given the symbol frequencies*/
static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree * tree, const unsigned * frequencies,
size_t mincodes, size_t numcodes, unsigned maxbitlen)
{
unsigned error = 0;
while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/
tree->lengths = (unsigned *)lodepng_malloc(numcodes * sizeof(unsigned));
if(!tree->lengths) return 83; /*alloc fail*/
tree->maxbitlen = maxbitlen;
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
if(!error) error = HuffmanTree_makeFromLengths2(tree);
return error;
}
#endif /*LODEPNG_COMPILE_ENCODER*/
/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
static unsigned generateFixedLitLenTree(HuffmanTree * tree)
{
unsigned i, error = 0;
unsigned * bitlen = (unsigned *)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
if(!bitlen) return 83; /*alloc fail*/
/*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
for(i = 0; i <= 143; ++i) bitlen[i] = 8;
for(i = 144; i <= 255; ++i) bitlen[i] = 9;
for(i = 256; i <= 279; ++i) bitlen[i] = 7;
for(i = 280; i <= 287; ++i) bitlen[i] = 8;
error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);
lodepng_free(bitlen);
return error;
}
/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
static unsigned generateFixedDistanceTree(HuffmanTree * tree)
{
unsigned i, error = 0;
unsigned * bitlen = (unsigned *)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
if(!bitlen) return 83; /*alloc fail*/
/*there are 32 distance codes, but 30-31 are unused*/
for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5;
error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);
lodepng_free(bitlen);
return error;
}
#ifdef LODEPNG_COMPILE_DECODER
/*
returns the code. The bit reader must already have been ensured at least 15 bits
*/
static unsigned huffmanDecodeSymbol(LodePNGBitReader * reader, const HuffmanTree * codetree)
{
unsigned short code = peekBits(reader, FIRSTBITS);
unsigned short l = codetree->table_len[code];
unsigned short value = codetree->table_value[code];
if(l <= FIRSTBITS) {
advanceBits(reader, l);
return value;
}
else {
unsigned index2;
advanceBits(reader, FIRSTBITS);
index2 = value + peekBits(reader, l - FIRSTBITS);
advanceBits(reader, codetree->table_len[index2] - FIRSTBITS);
return codetree->table_value[index2];
}
}
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_DECODER
/* ////////////////////////////////////////////////////////////////////////// */
/* / Inflator (Decompressor) / */
/* ////////////////////////////////////////////////////////////////////////// */
/*get the tree of a deflated block with fixed tree, as specified in the deflate specification
Returns error code.*/
static unsigned getTreeInflateFixed(HuffmanTree * tree_ll, HuffmanTree * tree_d)
{
unsigned error = generateFixedLitLenTree(tree_ll);
if(error) return error;
return generateFixedDistanceTree(tree_d);
}
/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
static unsigned getTreeInflateDynamic(HuffmanTree * tree_ll, HuffmanTree * tree_d,
LodePNGBitReader * reader)
{
/*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
unsigned error = 0;
unsigned n, HLIT, HDIST, HCLEN, i;
/*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
unsigned * bitlen_ll = 0; /*lit,len code lengths*/
unsigned * bitlen_d = 0; /*dist code lengths*/
/*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
unsigned * bitlen_cl = 0;
HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
if(!ensureBits17(reader, 14)) return 49; /*error: the bit pointer is or will go past the memory*/
/*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
HLIT = readBits(reader, 5) + 257;
/*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
HDIST = readBits(reader, 5) + 1;
/*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
HCLEN = readBits(reader, 4) + 4;
bitlen_cl = (unsigned *)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned));
if(!bitlen_cl) return 83 /*alloc fail*/;
HuffmanTree_init(&tree_cl);
while(!error) {
/*read the code length codes out of 3 * (amount of code length codes) bits*/
if(lodepng_gtofl(reader->bp, HCLEN * 3, reader->bitsize)) {
ERROR_BREAK(50); /*error: the bit pointer is or will go past the memory*/
}
for(i = 0; i != HCLEN; ++i) {
ensureBits9(reader, 3); /*out of bounds already checked above */
bitlen_cl[CLCL_ORDER[i]] = readBits(reader, 3);
}
for(i = HCLEN; i != NUM_CODE_LENGTH_CODES; ++i) {
bitlen_cl[CLCL_ORDER[i]] = 0;
}
error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);
if(error) break;
/*now we can use this tree to read the lengths for the tree that this function will return*/
bitlen_ll = (unsigned *)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
bitlen_d = (unsigned *)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);
lodepng_memset(bitlen_ll, 0, NUM_DEFLATE_CODE_SYMBOLS * sizeof(*bitlen_ll));
lodepng_memset(bitlen_d, 0, NUM_DISTANCE_SYMBOLS * sizeof(*bitlen_d));
/*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
i = 0;
while(i < HLIT + HDIST) {
unsigned code;
ensureBits25(reader, 22); /* up to 15 bits for huffman code, up to 7 extra bits below*/
code = huffmanDecodeSymbol(reader, &tree_cl);
if(code <= 15) { /*a length code*/
if(i < HLIT) bitlen_ll[i] = code;
else bitlen_d[i - HLIT] = code;
++i;
}
else if(code == 16) { /*repeat previous*/
unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/
unsigned value; /*set value to the previous code*/
if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
replength += readBits(reader, 2);
if(i < HLIT + 1) value = bitlen_ll[i - 1];
else value = bitlen_d[i - HLIT - 1];
/*repeat this value in the next lengths*/
for(n = 0; n < replength; ++n) {
if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
if(i < HLIT) bitlen_ll[i] = value;
else bitlen_d[i - HLIT] = value;
++i;
}
}
else if(code == 17) { /*repeat "0" 3-10 times*/
unsigned replength = 3; /*read in the bits that indicate repeat length*/
replength += readBits(reader, 3);
/*repeat this value in the next lengths*/
for(n = 0; n < replength; ++n) {
if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
if(i < HLIT) bitlen_ll[i] = 0;
else bitlen_d[i - HLIT] = 0;
++i;
}
}
else if(code == 18) { /*repeat "0" 11-138 times*/
unsigned replength = 11; /*read in the bits that indicate repeat length*/
replength += readBits(reader, 7);
/*repeat this value in the next lengths*/
for(n = 0; n < replength; ++n) {
if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
if(i < HLIT) bitlen_ll[i] = 0;
else bitlen_d[i - HLIT] = 0;
++i;
}
}
else { /*if(code == INVALIDSYMBOL)*/
ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/
}
/*check if any of the ensureBits above went out of bounds*/
if(reader->bp > reader->bitsize) {
/*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
(10=no endcode, 11=wrong jump outside of tree)*/
/* TODO: revise error codes 10,11,50: the above comment is no longer valid */
ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
}
}
if(error) break;
if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
/*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);
if(error) break;
error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);
break; /*end of error-while*/
}
lodepng_free(bitlen_cl);
lodepng_free(bitlen_ll);
lodepng_free(bitlen_d);
HuffmanTree_cleanup(&tree_cl);
return error;
}
/*inflate a block with dynamic of fixed Huffman tree. btype must be 1 or 2.*/
static unsigned inflateHuffmanBlock(ucvector * out, LodePNGBitReader * reader,
unsigned btype, size_t max_output_size)
{
unsigned error = 0;
HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/
HuffmanTree tree_d; /*the huffman tree for distance codes*/
HuffmanTree_init(&tree_ll);
HuffmanTree_init(&tree_d);
if(btype == 1) error = getTreeInflateFixed(&tree_ll, &tree_d);
else /*if(btype == 2)*/ error = getTreeInflateDynamic(&tree_ll, &tree_d, reader);
while(!error) { /*decode all symbols until end reached, breaks at end code*/
/*code_ll is literal, length or end code*/
unsigned code_ll;
ensureBits25(reader, 20); /* up to 15 for the huffman symbol, up to 5 for the length extra bits */
code_ll = huffmanDecodeSymbol(reader, &tree_ll);
if(code_ll <= 255) { /*literal symbol*/
if(!ucvector_resize(out, out->size + 1)) ERROR_BREAK(83 /*alloc fail*/);
out->data[out->size - 1] = (unsigned char)code_ll;
}
else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) { /*length code*/
unsigned code_d, distance;
unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/
size_t start, backward, length;
/*part 1: get length base*/
length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];
/*part 2: get extra bits and add the value of that to length*/
numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];
if(numextrabits_l != 0) {
/* bits already ensured above */
length += readBits(reader, numextrabits_l);
}
/*part 3: get distance code*/
ensureBits32(reader, 28); /* up to 15 for the huffman symbol, up to 13 for the extra bits */
code_d = huffmanDecodeSymbol(reader, &tree_d);
if(code_d > 29) {
if(code_d <= 31) {
ERROR_BREAK(18); /*error: invalid distance code (30-31 are never used)*/
}
else { /* if(code_d == INVALIDSYMBOL) */
ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/
}
}
distance = DISTANCEBASE[code_d];
/*part 4: get extra bits from distance*/
numextrabits_d = DISTANCEEXTRA[code_d];
if(numextrabits_d != 0) {
/* bits already ensured above */
distance += readBits(reader, numextrabits_d);
}
/*part 5: fill in all the out[n] values based on the length and dist*/
start = out->size;
if(distance > start) ERROR_BREAK(52); /*too long backward distance*/
backward = start - distance;
if(!ucvector_resize(out, out->size + length)) ERROR_BREAK(83 /*alloc fail*/);
if(distance < length) {
size_t forward;
lodepng_memcpy(out->data + start, out->data + backward, distance);
start += distance;
for(forward = distance; forward < length; ++forward) {
out->data[start++] = out->data[backward++];
}
}
else {
lodepng_memcpy(out->data + start, out->data + backward, length);
}
}
else if(code_ll == 256) {
break; /*end code, break the loop*/
}
else { /*if(code_ll == INVALIDSYMBOL)*/
ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/
}
/*check if any of the ensureBits above went out of bounds*/
if(reader->bp > reader->bitsize) {
/*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
(10=no endcode, 11=wrong jump outside of tree)*/
/* TODO: revise error codes 10,11,50: the above comment is no longer valid */
ERROR_BREAK(51); /*error, bit pointer jumps past memory*/
}
if(max_output_size && out->size > max_output_size) {
ERROR_BREAK(109); /*error, larger than max size*/
}
}
HuffmanTree_cleanup(&tree_ll);
HuffmanTree_cleanup(&tree_d);
return error;
}
static unsigned inflateNoCompression(ucvector * out, LodePNGBitReader * reader,
const LodePNGDecompressSettings * settings)
{
size_t bytepos;
size_t size = reader->size;
unsigned LEN, NLEN, error = 0;
/*go to first boundary of byte*/
bytepos = (reader->bp + 7u) >> 3u;
/*read LEN (2 bytes) and NLEN (2 bytes)*/
if(bytepos + 4 >= size) return 52; /*error, bit pointer will jump past memory*/
LEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u);
bytepos += 2;
NLEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u);
bytepos += 2;
/*check if 16-bit NLEN is really the one's complement of LEN*/
if(!settings->ignore_nlen && LEN + NLEN != 65535) {
return 21; /*error: NLEN is not one's complement of LEN*/
}
if(!ucvector_resize(out, out->size + LEN)) return 83; /*alloc fail*/
/*read the literal data: LEN bytes are now stored in the out buffer*/
if(bytepos + LEN > size) return 23; /*error: reading outside of in buffer*/
lodepng_memcpy(out->data + out->size - LEN, reader->data + bytepos, LEN);
bytepos += LEN;
reader->bp = bytepos << 3u;
return error;
}
static unsigned lodepng_inflatev(ucvector * out,
const unsigned char * in, size_t insize,
const LodePNGDecompressSettings * settings)
{
unsigned BFINAL = 0;
LodePNGBitReader reader;
unsigned error = LodePNGBitReader_init(&reader, in, insize);
if(error) return error;
while(!BFINAL) {
unsigned BTYPE;
if(!ensureBits9(&reader, 3)) return 52; /*error, bit pointer will jump past memory*/
BFINAL = readBits(&reader, 1);
BTYPE = readBits(&reader, 2);
if(BTYPE == 3) return 20; /*error: invalid BTYPE*/
else if(BTYPE == 0) error = inflateNoCompression(out, &reader, settings); /*no compression*/
else error = inflateHuffmanBlock(out, &reader, BTYPE, settings->max_output_size); /*compression, BTYPE 01 or 10*/
if(!error && settings->max_output_size && out->size > settings->max_output_size) error = 109;
if(error) break;
}
return error;
}
unsigned lodepng_inflate(unsigned char ** out, size_t * outsize,
const unsigned char * in, size_t insize,
const LodePNGDecompressSettings * settings)
{
ucvector v = ucvector_init(*out, *outsize);
unsigned error = lodepng_inflatev(&v, in, insize, settings);
*out = v.data;
*outsize = v.size;
return error;
}
static unsigned inflatev(ucvector * out, const unsigned char * in, size_t insize,
const LodePNGDecompressSettings * settings)
{
if(settings->custom_inflate) {
unsigned error = settings->custom_inflate(&out->data, &out->size, in, insize, settings);
out->allocsize = out->size;
if(error) {
/*the custom inflate is allowed to have its own error codes, however, we translate it to code 110*/
error = 110;
/*if there's a max output size, and the custom zlib returned error, then indicate that error instead*/
if(settings->max_output_size && out->size > settings->max_output_size) error = 109;
}
return error;
}
else {
return lodepng_inflatev(out, in, insize, settings);
}
}
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/* ////////////////////////////////////////////////////////////////////////// */
/* / Deflator (Compressor) / */
/* ////////////////////////////////////////////////////////////////////////// */
static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258;
/*search the index in the array, that has the largest value smaller than or equal to the given value,
given array must be sorted (if no value is smaller, it returns the size of the given array)*/
static size_t searchCodeIndex(const unsigned * array, size_t array_size, size_t value)
{
/*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/
size_t left = 1;
size_t right = array_size - 1;
while(left <= right) {
size_t mid = (left + right) >> 1;
if(array[mid] >= value) right = mid - 1;
else left = mid + 1;
}
if(left >= array_size || array[left] > value) left--;
return left;
}
static void addLengthDistance(uivector * values, size_t length, size_t distance)
{
/*values in encoded vector are those used by deflate:
0-255: literal bytes
256: end
257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)
286-287: invalid*/
unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length);
unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]);
unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance);
unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]);
size_t pos = values->size;
/*TODO: return error when this fails (out of memory)*/
unsigned ok = uivector_resize(values, values->size + 4);
if(ok) {
values->data[pos + 0] = length_code + FIRST_LENGTH_CODE_INDEX;
values->data[pos + 1] = extra_length;
values->data[pos + 2] = dist_code;
values->data[pos + 3] = extra_distance;
}
}
/*3 bytes of data get encoded into two bytes. The hash cannot use more than 3
bytes as input because 3 is the minimum match length for deflate*/
static const unsigned HASH_NUM_VALUES = 65536;
static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/
typedef struct Hash {
int * head; /*hash value to head circular pos - can be outdated if went around window*/
/*circular pos to prev circular pos*/
unsigned short * chain;
int * val; /*circular pos to hash value*/
/*TODO: do this not only for zeros but for any repeated byte. However for PNG
it's always going to be the zeros that dominate, so not important for PNG*/
int * headz; /*similar to head, but for chainz*/
unsigned short * chainz; /*those with same amount of zeros*/
unsigned short * zeros; /*length of zeros streak, used as a second hash chain*/
} Hash;
static unsigned hash_init(Hash * hash, unsigned windowsize)
{
unsigned i;
hash->head = (int *)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES);
hash->val = (int *)lodepng_malloc(sizeof(int) * windowsize);
hash->chain = (unsigned short *)lodepng_malloc(sizeof(unsigned short) * windowsize);
hash->zeros = (unsigned short *)lodepng_malloc(sizeof(unsigned short) * windowsize);
hash->headz = (int *)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1));
hash->chainz = (unsigned short *)lodepng_malloc(sizeof(unsigned short) * windowsize);
if(!hash->head || !hash->chain || !hash->val || !hash->headz || !hash->chainz || !hash->zeros) {
return 83; /*alloc fail*/
}
/*initialize hash table*/
for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1;
for(i = 0; i != windowsize; ++i) hash->val[i] = -1;
for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/
for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1;
for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/
return 0;
}
static void hash_cleanup(Hash * hash)
{
lodepng_free(hash->head);
lodepng_free(hash->val);
lodepng_free(hash->chain);
lodepng_free(hash->zeros);
lodepng_free(hash->headz);
lodepng_free(hash->chainz);
}
static unsigned getHash(const unsigned char * data, size_t size, size_t pos)
{
unsigned result = 0;
if(pos + 2 < size) {
/*A simple shift and xor hash is used. Since the data of PNGs is dominated
by zeroes due to the filters, a better hash does not have a significant
effect on speed in traversing the chain, and causes more time spend on
calculating the hash.*/
result ^= ((unsigned)data[pos + 0] << 0u);
result ^= ((unsigned)data[pos + 1] << 4u);
result ^= ((unsigned)data[pos + 2] << 8u);
}
else {
size_t amount, i;
if(pos >= size) return 0;
amount = size - pos;
for(i = 0; i != amount; ++i) result ^= ((unsigned)data[pos + i] << (i * 8u));
}
return result & HASH_BIT_MASK;
}
static unsigned countZeros(const unsigned char * data, size_t size, size_t pos)
{
const unsigned char * start = data + pos;
const unsigned char * end = start + MAX_SUPPORTED_DEFLATE_LENGTH;
if(end > data + size) end = data + size;
data = start;
while(data != end && *data == 0) ++data;
/*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/
return (unsigned)(data - start);
}
/*wpos = pos & (windowsize - 1)*/
static void updateHashChain(Hash * hash, size_t wpos, unsigned hashval, unsigned short numzeros)
{
hash->val[wpos] = (int)hashval;
if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval];
hash->head[hashval] = (int)wpos;
hash->zeros[wpos] = numzeros;
if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros];
hash->headz[numzeros] = (int)wpos;
}
/*
LZ77-encode the data. Return value is error code. The input are raw bytes, the output
is in the form of unsigned integers with codes representing for example literal bytes, or
length/distance pairs.
It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a
sliding window (of windowsize) is used, and all past bytes in that window can be used as
the "dictionary". A brute force search through all possible distances would be slow, and
this hash technique is one out of several ways to speed this up.
*/
static unsigned encodeLZ77(uivector * out, Hash * hash,
const unsigned char * in, size_t inpos, size_t insize, unsigned windowsize,
unsigned minmatch, unsigned nicematch, unsigned lazymatching)
{
size_t pos;
unsigned i, error = 0;
/*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/
unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8u;
unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64;
unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/
unsigned numzeros = 0;
unsigned offset; /*the offset represents the distance in LZ77 terminology*/
unsigned length;
unsigned lazy = 0;
unsigned lazylength = 0, lazyoffset = 0;
unsigned hashval;
unsigned current_offset, current_length;
unsigned prev_offset;
const unsigned char * lastptr, * foreptr, * backptr;
unsigned hashpos;
if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/
if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/
if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH;
for(pos = inpos; pos < insize; ++pos) {
size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/
unsigned chainlength = 0;
hashval = getHash(in, insize, pos);
if(usezeros && hashval == 0) {
if(numzeros == 0) numzeros = countZeros(in, insize, pos);
else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
}
else {
numzeros = 0;
}
updateHashChain(hash, wpos, hashval, numzeros);
/*the length and offset found for the current position*/
length = 0;
offset = 0;
hashpos = hash->chain[wpos];
lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH];
/*search for the longest string*/
prev_offset = 0;
for(;;) {
if(chainlength++ >= maxchainlength) break;
current_offset = (unsigned)(hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize);
if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/
prev_offset = current_offset;
if(current_offset > 0) {
/*test the next characters*/
foreptr = &in[pos];
backptr = &in[pos - current_offset];
/*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/
if(numzeros >= 3) {
unsigned skip = hash->zeros[hashpos];
if(skip > numzeros) skip = numzeros;
backptr += skip;
foreptr += skip;
}
while(foreptr != lastptr && *backptr == *foreptr) { /*maximum supported length by deflate is max length*/
++backptr;
++foreptr;
}
current_length = (unsigned)(foreptr - &in[pos]);
if(current_length > length) {
length = current_length; /*the longest length*/
offset = current_offset; /*the offset that is related to this longest length*/
/*jump out once a length of max length is found (speed gain). This also jumps
out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/
if(current_length >= nicematch) break;
}
}
if(hashpos == hash->chain[hashpos]) break;
if(numzeros >= 3 && length > numzeros) {
hashpos = hash->chainz[hashpos];
if(hash->zeros[hashpos] != numzeros) break;
}
else {
hashpos = hash->chain[hashpos];
/*outdated hash value, happens if particular value was not encountered in whole last window*/
if(hash->val[hashpos] != (int)hashval) break;
}
}
if(lazymatching) {
if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) {
lazy = 1;
lazylength = length;
lazyoffset = offset;
continue; /*try the next byte*/
}
if(lazy) {
lazy = 0;
if(pos == 0) ERROR_BREAK(81);
if(length > lazylength + 1) {
/*push the previous character as literal*/
if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/);
}
else {
length = lazylength;
offset = lazyoffset;
hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/
hash->headz[numzeros] = -1; /*idem*/
--pos;
}
}
}
if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/);
/*encode it as length/distance pair or literal value*/
if(length < 3) { /*only lengths of 3 or higher are supported as length/distance pair*/
if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
}
else if(length < minmatch || (length == 3 && offset > 4096)) {
/*compensate for the fact that longer offsets have more extra bits, a
length of only 3 may be not worth it then*/
if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
}
else {
addLengthDistance(out, length, offset);
for(i = 1; i < length; ++i) {
++pos;
wpos = pos & (windowsize - 1);
hashval = getHash(in, insize, pos);
if(usezeros && hashval == 0) {
if(numzeros == 0) numzeros = countZeros(in, insize, pos);
else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
}
else {
numzeros = 0;
}
updateHashChain(hash, wpos, hashval, numzeros);
}
}
} /*end of the loop through each character of input*/
return error;
}
/* /////////////////////////////////////////////////////////////////////////// */
static unsigned deflateNoCompression(ucvector * out, const unsigned char * data, size_t datasize)
{
/*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte,
2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/
size_t i, numdeflateblocks = (datasize + 65534u) / 65535u;
unsigned datapos = 0;
for(i = 0; i != numdeflateblocks; ++i) {
unsigned BFINAL, BTYPE, LEN, NLEN;
unsigned char firstbyte;
size_t pos = out->size;
BFINAL = (i == numdeflateblocks - 1);
BTYPE = 0;
LEN = 65535;
if(datasize - datapos < 65535u) LEN = (unsigned)datasize - datapos;
NLEN = 65535 - LEN;
if(!ucvector_resize(out, out->size + LEN + 5)) return 83; /*alloc fail*/
firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1u) << 1u) + ((BTYPE & 2u) << 1u));
out->data[pos + 0] = firstbyte;
out->data[pos + 1] = (unsigned char)(LEN & 255);
out->data[pos + 2] = (unsigned char)(LEN >> 8u);
out->data[pos + 3] = (unsigned char)(NLEN & 255);
out->data[pos + 4] = (unsigned char)(NLEN >> 8u);
lodepng_memcpy(out->data + pos + 5, data + datapos, LEN);
datapos += LEN;
}
return 0;
}
/*
write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.
tree_ll: the tree for lit and len codes.
tree_d: the tree for distance codes.
*/
static void writeLZ77data(LodePNGBitWriter * writer, const uivector * lz77_encoded,
const HuffmanTree * tree_ll, const HuffmanTree * tree_d)
{
size_t i = 0;
for(i = 0; i != lz77_encoded->size; ++i) {
unsigned val = lz77_encoded->data[i];
writeBitsReversed(writer, tree_ll->codes[val], tree_ll->lengths[val]);
if(val > 256) { /*for a length code, 3 more things have to be added*/
unsigned length_index = val - FIRST_LENGTH_CODE_INDEX;
unsigned n_length_extra_bits = LENGTHEXTRA[length_index];
unsigned length_extra_bits = lz77_encoded->data[++i];
unsigned distance_code = lz77_encoded->data[++i];
unsigned distance_index = distance_code;
unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index];
unsigned distance_extra_bits = lz77_encoded->data[++i];
writeBits(writer, length_extra_bits, n_length_extra_bits);
writeBitsReversed(writer, tree_d->codes[distance_code], tree_d->lengths[distance_code]);
writeBits(writer, distance_extra_bits, n_distance_extra_bits);
}
}
}
/*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/
static unsigned deflateDynamic(LodePNGBitWriter * writer, Hash * hash,
const unsigned char * data, size_t datapos, size_t dataend,
const LodePNGCompressSettings * settings, unsigned final)
{
unsigned error = 0;
/*
A block is compressed as follows: The PNG data is lz77 encoded, resulting in
literal bytes and length/distance pairs. This is then huffman compressed with
two huffman trees. One huffman tree is used for the lit and len values ("ll"),
another huffman tree is used for the dist values ("d"). These two trees are
stored using their code lengths, and to compress even more these code lengths
are also run-length encoded and huffman compressed. This gives a huffman tree
of code lengths "cl". The code lengths used to describe this third tree are
the code length code lengths ("clcl").
*/
/*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/
uivector lz77_encoded;
HuffmanTree tree_ll; /*tree for lit,len values*/
HuffmanTree tree_d; /*tree for distance codes*/
HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/
unsigned * frequencies_ll = 0; /*frequency of lit,len codes*/
unsigned * frequencies_d = 0; /*frequency of dist codes*/
unsigned * frequencies_cl = 0; /*frequency of code length codes*/
unsigned * bitlen_lld = 0; /*lit,len,dist code lengths (int bits), literally (without repeat codes).*/
unsigned * bitlen_lld_e = 0; /*bitlen_lld encoded with repeat codes (this is a rudimentary run length compression)*/
size_t datasize = dataend - datapos;
/*
If we could call "bitlen_cl" the the code length code lengths ("clcl"), that is the bit lengths of codes to represent
tree_cl in CLCL_ORDER, then due to the huffman compression of huffman tree representations ("two levels"), there are
some analogies:
bitlen_lld is to tree_cl what data is to tree_ll and tree_d.
bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.
bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.
*/
unsigned BFINAL = final;
size_t i;
size_t numcodes_ll, numcodes_d, numcodes_lld, numcodes_lld_e, numcodes_cl;
unsigned HLIT, HDIST, HCLEN;
uivector_init(&lz77_encoded);
HuffmanTree_init(&tree_ll);
HuffmanTree_init(&tree_d);
HuffmanTree_init(&tree_cl);
/* could fit on stack, but >1KB is on the larger side so allocate instead */
frequencies_ll = (unsigned *)lodepng_malloc(286 * sizeof(*frequencies_ll));
frequencies_d = (unsigned *)lodepng_malloc(30 * sizeof(*frequencies_d));
frequencies_cl = (unsigned *)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(*frequencies_cl));
if(!frequencies_ll || !frequencies_d || !frequencies_cl) error = 83; /*alloc fail*/
/*This while loop never loops due to a break at the end, it is here to
allow breaking out of it to the cleanup phase on error conditions.*/
while(!error) {
lodepng_memset(frequencies_ll, 0, 286 * sizeof(*frequencies_ll));
lodepng_memset(frequencies_d, 0, 30 * sizeof(*frequencies_d));
lodepng_memset(frequencies_cl, 0, NUM_CODE_LENGTH_CODES * sizeof(*frequencies_cl));
if(settings->use_lz77) {
error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
settings->minmatch, settings->nicematch, settings->lazymatching);
if(error) break;
}
else {
if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/);
for(i = datapos; i < dataend;
++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/
}
/*Count the frequencies of lit, len and dist codes*/
for(i = 0; i != lz77_encoded.size; ++i) {
unsigned symbol = lz77_encoded.data[i];
++frequencies_ll[symbol];
if(symbol > 256) {
unsigned dist = lz77_encoded.data[i + 2];
++frequencies_d[dist];
i += 3;
}
}
frequencies_ll[256] = 1; /*there will be exactly 1 end code, at the end of the block*/
/*Make both huffman trees, one for the lit and len codes, one for the dist codes*/
error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll, 257, 286, 15);
if(error) break;
/*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/
error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d, 2, 30, 15);
if(error) break;
numcodes_ll = LODEPNG_MIN(tree_ll.numcodes, 286);
numcodes_d = LODEPNG_MIN(tree_d.numcodes, 30);
/*store the code lengths of both generated trees in bitlen_lld*/
numcodes_lld = numcodes_ll + numcodes_d;
bitlen_lld = (unsigned *)lodepng_malloc(numcodes_lld * sizeof(*bitlen_lld));
/*numcodes_lld_e never needs more size than bitlen_lld*/
bitlen_lld_e = (unsigned *)lodepng_malloc(numcodes_lld * sizeof(*bitlen_lld_e));
if(!bitlen_lld || !bitlen_lld_e) ERROR_BREAK(83); /*alloc fail*/
numcodes_lld_e = 0;
for(i = 0; i != numcodes_ll; ++i) bitlen_lld[i] = tree_ll.lengths[i];
for(i = 0; i != numcodes_d; ++i) bitlen_lld[numcodes_ll + i] = tree_d.lengths[i];
/*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times),
17 (3-10 zeroes), 18 (11-138 zeroes)*/
for(i = 0; i != numcodes_lld; ++i) {
unsigned j = 0; /*amount of repetitions*/
while(i + j + 1 < numcodes_lld && bitlen_lld[i + j + 1] == bitlen_lld[i]) ++j;
if(bitlen_lld[i] == 0 && j >= 2) { /*repeat code for zeroes*/
++j; /*include the first zero*/
if(j <= 10) { /*repeat code 17 supports max 10 zeroes*/
bitlen_lld_e[numcodes_lld_e++] = 17;
bitlen_lld_e[numcodes_lld_e++] = j - 3;
}
else { /*repeat code 18 supports max 138 zeroes*/
if(j > 138) j = 138;
bitlen_lld_e[numcodes_lld_e++] = 18;
bitlen_lld_e[numcodes_lld_e++] = j - 11;
}
i += (j - 1);
}
else if(j >= 3) { /*repeat code for value other than zero*/
size_t k;
unsigned num = j / 6u, rest = j % 6u;
bitlen_lld_e[numcodes_lld_e++] = bitlen_lld[i];
for(k = 0; k < num; ++k) {
bitlen_lld_e[numcodes_lld_e++] = 16;
bitlen_lld_e[numcodes_lld_e++] = 6 - 3;
}
if(rest >= 3) {
bitlen_lld_e[numcodes_lld_e++] = 16;
bitlen_lld_e[numcodes_lld_e++] = rest - 3;
}
else j -= rest;
i += j;
}
else { /*too short to benefit from repeat code*/
bitlen_lld_e[numcodes_lld_e++] = bitlen_lld[i];
}
}
/*generate tree_cl, the huffmantree of huffmantrees*/
for(i = 0; i != numcodes_lld_e; ++i) {
++frequencies_cl[bitlen_lld_e[i]];
/*after a repeat code come the bits that specify the number of repetitions,
those don't need to be in the frequencies_cl calculation*/
if(bitlen_lld_e[i] >= 16) ++i;
}
error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl,
NUM_CODE_LENGTH_CODES, NUM_CODE_LENGTH_CODES, 7);
if(error) break;
/*compute amount of code-length-code-lengths to output*/
numcodes_cl = NUM_CODE_LENGTH_CODES;
/*trim zeros at the end (using CLCL_ORDER), but minimum size must be 4 (see HCLEN below)*/
while(numcodes_cl > 4u && tree_cl.lengths[CLCL_ORDER[numcodes_cl - 1u]] == 0) {
numcodes_cl--;
}
/*
Write everything into the output
After the BFINAL and BTYPE, the dynamic block consists out of the following:
- 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN
- (HCLEN+4)*3 bits code lengths of code length alphabet
- HLIT + 257 code lengths of lit/length alphabet (encoded using the code length
alphabet, + possible repetition codes 16, 17, 18)
- HDIST + 1 code lengths of distance alphabet (encoded using the code length
alphabet, + possible repetition codes 16, 17, 18)
- compressed data
- 256 (end code)
*/
/*Write block type*/
writeBits(writer, BFINAL, 1);
writeBits(writer, 0, 1); /*first bit of BTYPE "dynamic"*/
writeBits(writer, 1, 1); /*second bit of BTYPE "dynamic"*/
/*write the HLIT, HDIST and HCLEN values*/
/*all three sizes take trimmed ending zeroes into account, done either by HuffmanTree_makeFromFrequencies
or in the loop for numcodes_cl above, which saves space. */
HLIT = (unsigned)(numcodes_ll - 257);
HDIST = (unsigned)(numcodes_d - 1);
HCLEN = (unsigned)(numcodes_cl - 4);
writeBits(writer, HLIT, 5);
writeBits(writer, HDIST, 5);
writeBits(writer, HCLEN, 4);
/*write the code lengths of the code length alphabet ("bitlen_cl")*/
for(i = 0; i != numcodes_cl; ++i) writeBits(writer, tree_cl.lengths[CLCL_ORDER[i]], 3);
/*write the lengths of the lit/len AND the dist alphabet*/
for(i = 0; i != numcodes_lld_e; ++i) {
writeBitsReversed(writer, tree_cl.codes[bitlen_lld_e[i]], tree_cl.lengths[bitlen_lld_e[i]]);
/*extra bits of repeat codes*/
if(bitlen_lld_e[i] == 16) writeBits(writer, bitlen_lld_e[++i], 2);
else if(bitlen_lld_e[i] == 17) writeBits(writer, bitlen_lld_e[++i], 3);
else if(bitlen_lld_e[i] == 18) writeBits(writer, bitlen_lld_e[++i], 7);
}
/*write the compressed data symbols*/
writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d);
/*error: the length of the end code 256 must be larger than 0*/
if(tree_ll.lengths[256] == 0) ERROR_BREAK(64);
/*write the end code*/
writeBitsReversed(writer, tree_ll.codes[256], tree_ll.lengths[256]);
break; /*end of error-while*/
}
/*cleanup*/
uivector_cleanup(&lz77_encoded);
HuffmanTree_cleanup(&tree_ll);
HuffmanTree_cleanup(&tree_d);
HuffmanTree_cleanup(&tree_cl);
lodepng_free(frequencies_ll);
lodepng_free(frequencies_d);
lodepng_free(frequencies_cl);
lodepng_free(bitlen_lld);
lodepng_free(bitlen_lld_e);
return error;
}
static unsigned deflateFixed(LodePNGBitWriter * writer, Hash * hash,
const unsigned char * data,
size_t datapos, size_t dataend,
const LodePNGCompressSettings * settings, unsigned final)
{
HuffmanTree tree_ll; /*tree for literal values and length codes*/
HuffmanTree tree_d; /*tree for distance codes*/
unsigned BFINAL = final;
unsigned error = 0;
size_t i;
HuffmanTree_init(&tree_ll);
HuffmanTree_init(&tree_d);
error = generateFixedLitLenTree(&tree_ll);
if(!error) error = generateFixedDistanceTree(&tree_d);
if(!error) {
writeBits(writer, BFINAL, 1);
writeBits(writer, 1, 1); /*first bit of BTYPE*/
writeBits(writer, 0, 1); /*second bit of BTYPE*/
if(settings->use_lz77) { /*LZ77 encoded*/
uivector lz77_encoded;
uivector_init(&lz77_encoded);
error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
settings->minmatch, settings->nicematch, settings->lazymatching);
if(!error) writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d);
uivector_cleanup(&lz77_encoded);
}
else { /*no LZ77, but still will be Huffman compressed*/
for(i = datapos; i < dataend; ++i) {
writeBitsReversed(writer, tree_ll.codes[data[i]], tree_ll.lengths[data[i]]);
}
}
/*add END code*/
if(!error) writeBitsReversed(writer, tree_ll.codes[256], tree_ll.lengths[256]);
}
/*cleanup*/
HuffmanTree_cleanup(&tree_ll);
HuffmanTree_cleanup(&tree_d);
return error;
}
static unsigned lodepng_deflatev(ucvector * out, const unsigned char * in, size_t insize,
const LodePNGCompressSettings * settings)
{
unsigned error = 0;
size_t i, blocksize, numdeflateblocks;
Hash hash;
LodePNGBitWriter writer;
LodePNGBitWriter_init(&writer, out);
if(settings->btype > 2) return 61;
else if(settings->btype == 0) return deflateNoCompression(out, in, insize);
else if(settings->btype == 1) blocksize = insize;
else { /*if(settings->btype == 2)*/
/*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/
blocksize = insize / 8u + 8;
if(blocksize < 65536) blocksize = 65536;
if(blocksize > 262144) blocksize = 262144;
}
numdeflateblocks = (insize + blocksize - 1) / blocksize;
if(numdeflateblocks == 0) numdeflateblocks = 1;
error = hash_init(&hash, settings->windowsize);
if(!error) {
for(i = 0; i != numdeflateblocks && !error; ++i) {
unsigned final = (i == numdeflateblocks - 1);
size_t start = i * blocksize;
size_t end = start + blocksize;
if(end > insize) end = insize;
if(settings->btype == 1) error = deflateFixed(&writer, &hash, in, start, end, settings, final);
else if(settings->btype == 2) error = deflateDynamic(&writer, &hash, in, start, end, settings, final);
}
}
hash_cleanup(&hash);
return error;
}
unsigned lodepng_deflate(unsigned char ** out, size_t * outsize,
const unsigned char * in, size_t insize,
const LodePNGCompressSettings * settings)
{
ucvector v = ucvector_init(*out, *outsize);
unsigned error = lodepng_deflatev(&v, in, insize, settings);
*out = v.data;
*outsize = v.size;
return error;
}
static unsigned deflate(unsigned char ** out, size_t * outsize,
const unsigned char * in, size_t insize,
const LodePNGCompressSettings * settings)
{
if(settings->custom_deflate) {
unsigned error = settings->custom_deflate(out, outsize, in, insize, settings);
/*the custom deflate is allowed to have its own error codes, however, we translate it to code 111*/
return error ? 111 : 0;
}
else {
return lodepng_deflate(out, outsize, in, insize, settings);
}
}
#endif /*LODEPNG_COMPILE_DECODER*/
/* ////////////////////////////////////////////////////////////////////////// */
/* / Adler32 / */
/* ////////////////////////////////////////////////////////////////////////// */
static unsigned update_adler32(unsigned adler, const unsigned char * data, unsigned len)
{
unsigned s1 = adler & 0xffffu;
unsigned s2 = (adler >> 16u) & 0xffffu;
while(len != 0u) {
unsigned i;
/*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/
unsigned amount = len > 5552u ? 5552u : len;
len -= amount;
for(i = 0; i != amount; ++i) {
s1 += (*data++);
s2 += s1;
}
s1 %= 65521u;
s2 %= 65521u;
}
return (s2 << 16u) | s1;
}
/*Return the adler32 of the bytes data[0..len-1]*/
static unsigned adler32(const unsigned char * data, unsigned len)
{
return update_adler32(1u, data, len);
}
/* ////////////////////////////////////////////////////////////////////////// */
/* / Zlib / */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_DECODER
static unsigned lodepng_zlib_decompressv(ucvector * out,
const unsigned char * in, size_t insize,
const LodePNGDecompressSettings * settings)
{
unsigned error = 0;
unsigned CM, CINFO, FDICT;
if(insize < 2) return 53; /*error, size of zlib data too small*/
/*read information from zlib header*/
if((in[0] * 256 + in[1]) % 31 != 0) {
/*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
return 24;
}
CM = in[0] & 15;
CINFO = (in[0] >> 4) & 15;
/*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
FDICT = (in[1] >> 5) & 1;
/*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
if(CM != 8 || CINFO > 7) {
/*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/
return 25;
}
if(FDICT != 0) {
/*error: the specification of PNG says about the zlib stream:
"The additional flags shall not specify a preset dictionary."*/
return 26;
}
error = inflatev(out, in + 2, insize - 2, settings);
if(error) return error;
if(!settings->ignore_adler32) {
unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]);
unsigned checksum = adler32(out->data, (unsigned)(out->size));
if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/
}
return 0; /*no error*/
}
unsigned lodepng_zlib_decompress(unsigned char ** out, size_t * outsize, const unsigned char * in,
size_t insize, const LodePNGDecompressSettings * settings)
{
ucvector v = ucvector_init(*out, *outsize);
unsigned error = lodepng_zlib_decompressv(&v, in, insize, settings);
*out = v.data;
*outsize = v.size;
return error;
}
/*expected_size is expected output size, to avoid intermediate allocations. Set to 0 if not known. */
static unsigned zlib_decompress(unsigned char ** out, size_t * outsize, size_t expected_size,
const unsigned char * in, size_t insize, const LodePNGDecompressSettings * settings)
{
unsigned error;
if(settings->custom_zlib) {
error = settings->custom_zlib(out, outsize, in, insize, settings);
if(error) {
/*the custom zlib is allowed to have its own error codes, however, we translate it to code 110*/
error = 110;
/*if there's a max output size, and the custom zlib returned error, then indicate that error instead*/
if(settings->max_output_size && *outsize > settings->max_output_size) error = 109;
}
}
else {
ucvector v = ucvector_init(*out, *outsize);
if(expected_size) {
/*reserve the memory to avoid intermediate reallocations*/
ucvector_resize(&v, *outsize + expected_size);
v.size = *outsize;
}
error = lodepng_zlib_decompressv(&v, in, insize, settings);
*out = v.data;
*outsize = v.size;
}
return error;
}
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
unsigned lodepng_zlib_compress(unsigned char ** out, size_t * outsize, const unsigned char * in,
size_t insize, const LodePNGCompressSettings * settings)
{
size_t i;
unsigned error;
unsigned char * deflatedata = 0;
size_t deflatesize = 0;
error = deflate(&deflatedata, &deflatesize, in, insize, settings);
*out = NULL;
*outsize = 0;
if(!error) {
*outsize = deflatesize + 6;
*out = (unsigned char *)lodepng_malloc(*outsize);
if(!*out) error = 83; /*alloc fail*/
}
if(!error) {
unsigned ADLER32 = adler32(in, (unsigned)insize);
/*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/
unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/
unsigned FLEVEL = 0;
unsigned FDICT = 0;
unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64;
unsigned FCHECK = 31 - CMFFLG % 31;
CMFFLG += FCHECK;
(*out)[0] = (unsigned char)(CMFFLG >> 8);
(*out)[1] = (unsigned char)(CMFFLG & 255);
for(i = 0; i != deflatesize; ++i)(*out)[i + 2] = deflatedata[i];
lodepng_set32bitInt(&(*out)[*outsize - 4], ADLER32);
}
lodepng_free(deflatedata);
return error;
}
/* compress using the default or custom zlib function */
static unsigned zlib_compress(unsigned char ** out, size_t * outsize, const unsigned char * in,
size_t insize, const LodePNGCompressSettings * settings)
{
if(settings->custom_zlib) {
unsigned error = settings->custom_zlib(out, outsize, in, insize, settings);
/*the custom zlib is allowed to have its own error codes, however, we translate it to code 111*/
return error ? 111 : 0;
}
else {
return lodepng_zlib_compress(out, outsize, in, insize, settings);
}
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#else /*no LODEPNG_COMPILE_ZLIB*/
#ifdef LODEPNG_COMPILE_DECODER
static unsigned zlib_decompress(unsigned char ** out, size_t * outsize, size_t expected_size,
const unsigned char * in, size_t insize, const LodePNGDecompressSettings * settings)
{
if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
LV_UNUSED(expected_size);
return settings->custom_zlib(out, outsize, in, insize, settings);
}
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
static unsigned zlib_compress(unsigned char ** out, size_t * outsize, const unsigned char * in,
size_t insize, const LodePNGCompressSettings * settings)
{
if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
return settings->custom_zlib(out, outsize, in, insize, settings);
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_ZLIB*/
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_ENCODER
/*this is a good tradeoff between speed and compression ratio*/
#define DEFAULT_WINDOWSIZE 2048
void lodepng_compress_settings_init(LodePNGCompressSettings * settings)
{
/*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/
settings->btype = 2;
settings->use_lz77 = 1;
settings->windowsize = DEFAULT_WINDOWSIZE;
settings->minmatch = 3;
settings->nicematch = 128;
settings->lazymatching = 1;
settings->custom_zlib = 0;
settings->custom_deflate = 0;
settings->custom_context = 0;
}
const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0};
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_DECODER
void lodepng_decompress_settings_init(LodePNGDecompressSettings * settings)
{
settings->ignore_adler32 = 0;
settings->ignore_nlen = 0;
settings->max_output_size = 0;
settings->custom_zlib = 0;
settings->custom_inflate = 0;
settings->custom_context = 0;
}
const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0, 0, 0};
#endif /*LODEPNG_COMPILE_DECODER*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // End of Zlib related code. Begin of PNG related code. // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_PNG
/* ////////////////////////////////////////////////////////////////////////// */
/* / CRC32 / */
/* ////////////////////////////////////////////////////////////////////////// */
#ifndef LODEPNG_NO_COMPILE_CRC
/* CRC polynomial: 0xedb88320 */
static unsigned lodepng_crc32_table[256] = {
0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u,
249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u,
498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u,
325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u,
997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u,
901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u,
651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u,
671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u,
1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u,
2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u,
1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u,
1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u,
1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u,
1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u,
1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u,
1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u,
3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u,
3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u,
4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u,
4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u,
3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u,
3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u,
3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u,
3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u,
2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u,
2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u,
2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u,
2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u,
2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u,
2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u,
3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u,
3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u
};
/*Return the CRC of the bytes buf[0..len-1].*/
unsigned lodepng_crc32(const unsigned char * data, size_t length)
{
unsigned r = 0xffffffffu;
size_t i;
for(i = 0; i < length; ++i) {
r = lodepng_crc32_table[(r ^ data[i]) & 0xffu] ^ (r >> 8u);
}
return r ^ 0xffffffffu;
}
#else /* !LODEPNG_NO_COMPILE_CRC */
unsigned lodepng_crc32(const unsigned char * data, size_t length);
#endif /* !LODEPNG_NO_COMPILE_CRC */
/* ////////////////////////////////////////////////////////////////////////// */
/* / Reading and writing PNG color channel bits / */
/* ////////////////////////////////////////////////////////////////////////// */
/* The color channel bits of less-than-8-bit pixels are read with the MSB of bytes first,
so LodePNGBitWriter and LodePNGBitReader can't be used for those. */
static unsigned char readBitFromReversedStream(size_t * bitpointer, const unsigned char * bitstream)
{
unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1);
++(*bitpointer);
return result;
}
/* TODO: make this faster */
static unsigned readBitsFromReversedStream(size_t * bitpointer, const unsigned char * bitstream, size_t nbits)
{
unsigned result = 0;
size_t i;
for(i = 0 ; i < nbits; ++i) {
result <<= 1u;
result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream);
}
return result;
}
static void setBitOfReversedStream(size_t * bitpointer, unsigned char * bitstream, unsigned char bit)
{
/*the current bit in bitstream may be 0 or 1 for this to work*/
if(bit == 0) bitstream[(*bitpointer) >> 3u] &= (unsigned char)(~(1u << (7u - ((*bitpointer) & 7u))));
else bitstream[(*bitpointer) >> 3u] |= (1u << (7u - ((*bitpointer) & 7u)));
++(*bitpointer);
}
/* ////////////////////////////////////////////////////////////////////////// */
/* / PNG chunks / */
/* ////////////////////////////////////////////////////////////////////////// */
unsigned lodepng_chunk_length(const unsigned char * chunk)
{
return lodepng_read32bitInt(&chunk[0]);
}
void lodepng_chunk_type(char type[5], const unsigned char * chunk)
{
unsigned i;
for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i];
type[4] = 0; /*null termination char*/
}
unsigned char lodepng_chunk_type_equals(const unsigned char * chunk, const char * type)
{
if(lodepng_strlen(type) != 4) return 0;
return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]);
}
unsigned char lodepng_chunk_ancillary(const unsigned char * chunk)
{
return((chunk[4] & 32) != 0);
}
unsigned char lodepng_chunk_private(const unsigned char * chunk)
{
return((chunk[6] & 32) != 0);
}
unsigned char lodepng_chunk_safetocopy(const unsigned char * chunk)
{
return((chunk[7] & 32) != 0);
}
unsigned char * lodepng_chunk_data(unsigned char * chunk)
{
return &chunk[8];
}
const unsigned char * lodepng_chunk_data_const(const unsigned char * chunk)
{
return &chunk[8];
}
unsigned lodepng_chunk_check_crc(const unsigned char * chunk)
{
unsigned length = lodepng_chunk_length(chunk);
unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]);
/*the CRC is taken of the data and the 4 chunk type letters, not the length*/
unsigned checksum = lodepng_crc32(&chunk[4], length + 4);
if(CRC != checksum) return 1;
else return 0;
}
void lodepng_chunk_generate_crc(unsigned char * chunk)
{
unsigned length = lodepng_chunk_length(chunk);
unsigned CRC = lodepng_crc32(&chunk[4], length + 4);
lodepng_set32bitInt(chunk + 8 + length, CRC);
}
unsigned char * lodepng_chunk_next(unsigned char * chunk, unsigned char * end)
{
if(chunk >= end || end - chunk < 12) return end; /*too small to contain a chunk*/
if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47
&& chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) {
/* Is PNG magic header at start of PNG file. Jump to first actual chunk. */
return chunk + 8;
}
else {
size_t total_chunk_length;
unsigned char * result;
if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return end;
result = chunk + total_chunk_length;
if(result < chunk) return end; /*pointer overflow*/
return result;
}
}
const unsigned char * lodepng_chunk_next_const(const unsigned char * chunk, const unsigned char * end)
{
if(chunk >= end || end - chunk < 12) return end; /*too small to contain a chunk*/
if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47
&& chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) {
/* Is PNG magic header at start of PNG file. Jump to first actual chunk. */
return chunk + 8;
}
else {
size_t total_chunk_length;
const unsigned char * result;
if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return end;
result = chunk + total_chunk_length;
if(result < chunk) return end; /*pointer overflow*/
return result;
}
}
unsigned char * lodepng_chunk_find(unsigned char * chunk, unsigned char * end, const char type[5])
{
for(;;) {
if(chunk >= end || end - chunk < 12) return 0; /* past file end: chunk + 12 > end */
if(lodepng_chunk_type_equals(chunk, type)) return chunk;
chunk = lodepng_chunk_next(chunk, end);
}
return 0; /*Shouldn't reach this*/
}
const unsigned char * lodepng_chunk_find_const(const unsigned char * chunk, const unsigned char * end,
const char type[5])
{
for(;;) {
if(chunk >= end || end - chunk < 12) return 0; /* past file end: chunk + 12 > end */
if(lodepng_chunk_type_equals(chunk, type)) return chunk;
chunk = lodepng_chunk_next_const(chunk, end);
}
return 0; /*Shouldn't reach this*/
}
unsigned lodepng_chunk_append(unsigned char ** out, size_t * outsize, const unsigned char * chunk)
{
unsigned i;
size_t total_chunk_length, new_length;
unsigned char * chunk_start, * new_buffer;
if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return 77;
if(lodepng_addofl(*outsize, total_chunk_length, &new_length)) return 77;
new_buffer = (unsigned char *)lodepng_realloc(*out, new_length);
if(!new_buffer) return 83; /*alloc fail*/
(*out) = new_buffer;
(*outsize) = new_length;
chunk_start = &(*out)[new_length - total_chunk_length];
for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i];
return 0;
}
/*Sets length and name and allocates the space for data and crc but does not
set data or crc yet. Returns the start of the chunk in chunk. The start of
the data is at chunk + 8. To finalize chunk, add the data, then use
lodepng_chunk_generate_crc */
static unsigned lodepng_chunk_init(unsigned char ** chunk,
ucvector * out,
unsigned length, const char * type)
{
size_t new_length = out->size;
if(lodepng_addofl(new_length, length, &new_length)) return 77;
if(lodepng_addofl(new_length, 12, &new_length)) return 77;
if(!ucvector_resize(out, new_length)) return 83; /*alloc fail*/
*chunk = out->data + new_length - length - 12u;
/*1: length*/
lodepng_set32bitInt(*chunk, length);
/*2: chunk name (4 letters)*/
lodepng_memcpy(*chunk + 4, type, 4);
return 0;
}
/* like lodepng_chunk_create but with custom allocsize */
static unsigned lodepng_chunk_createv(ucvector * out,
unsigned length, const char * type, const unsigned char * data)
{
unsigned char * chunk;
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, length, type));
/*3: the data*/
lodepng_memcpy(chunk + 8, data, length);
/*4: CRC (of the chunkname characters and the data)*/
lodepng_chunk_generate_crc(chunk);
return 0;
}
unsigned lodepng_chunk_create(unsigned char ** out, size_t * outsize,
unsigned length, const char * type, const unsigned char * data)
{
ucvector v = ucvector_init(*out, *outsize);
unsigned error = lodepng_chunk_createv(&v, length, type, data);
*out = v.data;
*outsize = v.size;
return error;
}
/* ////////////////////////////////////////////////////////////////////////// */
/* / Color types, channels, bits / */
/* ////////////////////////////////////////////////////////////////////////// */
/*checks if the colortype is valid and the bitdepth bd is allowed for this colortype.
Return value is a LodePNG error code.*/
static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd)
{
switch(colortype) {
case LCT_GREY:
if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37;
break;
case LCT_RGB:
if(!(bd == 8 || bd == 16)) return 37;
break;
case LCT_PALETTE:
if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8)) return 37;
break;
case LCT_GREY_ALPHA:
if(!(bd == 8 || bd == 16)) return 37;
break;
case LCT_RGBA:
if(!(bd == 8 || bd == 16)) return 37;
break;
case LCT_MAX_OCTET_VALUE:
return 31; /* invalid color type */
default:
return 31; /* invalid color type */
}
return 0; /*allowed color type / bits combination*/
}
static unsigned getNumColorChannels(LodePNGColorType colortype)
{
switch(colortype) {
case LCT_GREY:
return 1;
case LCT_RGB:
return 3;
case LCT_PALETTE:
return 1;
case LCT_GREY_ALPHA:
return 2;
case LCT_RGBA:
return 4;
case LCT_MAX_OCTET_VALUE:
return 0; /* invalid color type */
default:
return 0; /*invalid color type*/
}
}
static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth)
{
/*bits per pixel is amount of channels * bits per channel*/
return getNumColorChannels(colortype) * bitdepth;
}
/* ////////////////////////////////////////////////////////////////////////// */
void lodepng_color_mode_init(LodePNGColorMode * info)
{
info->key_defined = 0;
info->key_r = info->key_g = info->key_b = 0;
info->colortype = LCT_RGBA;
info->bitdepth = 8;
info->palette = 0;
info->palettesize = 0;
}
/*allocates palette memory if needed, and initializes all colors to black*/
static void lodepng_color_mode_alloc_palette(LodePNGColorMode * info)
{
size_t i;
/*if the palette is already allocated, it will have size 1024 so no reallocation needed in that case*/
/*the palette must have room for up to 256 colors with 4 bytes each.*/
if(!info->palette) info->palette = (unsigned char *)lodepng_malloc(1024);
if(!info->palette) return; /*alloc fail*/
for(i = 0; i != 256; ++i) {
/*Initialize all unused colors with black, the value used for invalid palette indices.
This is an error according to the PNG spec, but common PNG decoders make it black instead.
That makes color conversion slightly faster due to no error handling needed.*/
info->palette[i * 4 + 0] = 0;
info->palette[i * 4 + 1] = 0;
info->palette[i * 4 + 2] = 0;
info->palette[i * 4 + 3] = 255;
}
}
void lodepng_color_mode_cleanup(LodePNGColorMode * info)
{
lodepng_palette_clear(info);
}
unsigned lodepng_color_mode_copy(LodePNGColorMode * dest, const LodePNGColorMode * source)
{
lodepng_color_mode_cleanup(dest);
lodepng_memcpy(dest, source, sizeof(LodePNGColorMode));
if(source->palette) {
dest->palette = (unsigned char *)lodepng_malloc(1024);
if(!dest->palette && source->palettesize) return 83; /*alloc fail*/
lodepng_memcpy(dest->palette, source->palette, source->palettesize * 4);
}
return 0;
}
LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth)
{
LodePNGColorMode result;
lodepng_color_mode_init(&result);
result.colortype = colortype;
result.bitdepth = bitdepth;
return result;
}
static int lodepng_color_mode_equal(const LodePNGColorMode * a, const LodePNGColorMode * b)
{
size_t i;
if(a->colortype != b->colortype) return 0;
if(a->bitdepth != b->bitdepth) return 0;
if(a->key_defined != b->key_defined) return 0;
if(a->key_defined) {
if(a->key_r != b->key_r) return 0;
if(a->key_g != b->key_g) return 0;
if(a->key_b != b->key_b) return 0;
}
if(a->palettesize != b->palettesize) return 0;
for(i = 0; i != a->palettesize * 4; ++i) {
if(a->palette[i] != b->palette[i]) return 0;
}
return 1;
}
void lodepng_palette_clear(LodePNGColorMode * info)
{
if(info->palette) lodepng_free(info->palette);
info->palette = 0;
info->palettesize = 0;
}
unsigned lodepng_palette_add(LodePNGColorMode * info,
unsigned char r, unsigned char g, unsigned char b, unsigned char a)
{
if(!info->palette) { /*allocate palette if empty*/
lodepng_color_mode_alloc_palette(info);
if(!info->palette) return 83; /*alloc fail*/
}
if(info->palettesize >= 256) {
return 108; /*too many palette values*/
}
info->palette[4 * info->palettesize + 0] = r;
info->palette[4 * info->palettesize + 1] = g;
info->palette[4 * info->palettesize + 2] = b;
info->palette[4 * info->palettesize + 3] = a;
++info->palettesize;
return 0;
}
/*calculate bits per pixel out of colortype and bitdepth*/
unsigned lodepng_get_bpp(const LodePNGColorMode * info)
{
return lodepng_get_bpp_lct(info->colortype, info->bitdepth);
}
unsigned lodepng_get_channels(const LodePNGColorMode * info)
{
return getNumColorChannels(info->colortype);
}
unsigned lodepng_is_greyscale_type(const LodePNGColorMode * info)
{
return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA;
}
unsigned lodepng_is_alpha_type(const LodePNGColorMode * info)
{
return (info->colortype & 4) != 0; /*4 or 6*/
}
unsigned lodepng_is_palette_type(const LodePNGColorMode * info)
{
return info->colortype == LCT_PALETTE;
}
unsigned lodepng_has_palette_alpha(const LodePNGColorMode * info)
{
size_t i;
for(i = 0; i != info->palettesize; ++i) {
if(info->palette[i * 4 + 3] < 255) return 1;
}
return 0;
}
unsigned lodepng_can_have_alpha(const LodePNGColorMode * info)
{
return info->key_defined
|| lodepng_is_alpha_type(info)
|| lodepng_has_palette_alpha(info);
}
static size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
{
size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth);
size_t n = (size_t)w * (size_t)h;
return ((n / 8u) * bpp) + ((n & 7u) * bpp + 7u) / 8u;
}
size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode * color)
{
return lodepng_get_raw_size_lct(w, h, color->colortype, color->bitdepth);
}
#ifdef LODEPNG_COMPILE_PNG
/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer,
and in addition has one extra byte per line: the filter byte. So this gives a larger
result than lodepng_get_raw_size. Set h to 1 to get the size of 1 row including filter byte. */
static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, unsigned bpp)
{
/* + 1 for the filter byte, and possibly plus padding bits per line. */
/* Ignoring casts, the expression is equal to (w * bpp + 7) / 8 + 1, but avoids overflow of w * bpp */
size_t line = ((size_t)(w / 8u) * bpp) + 1u + ((w & 7u) * bpp + 7u) / 8u;
return (size_t)h * line;
}
#ifdef LODEPNG_COMPILE_DECODER
/*Safely checks whether size_t overflow can be caused due to amount of pixels.
This check is overcautious rather than precise. If this check indicates no overflow,
you can safely compute in a size_t (but not an unsigned):
-(size_t)w * (size_t)h * 8
-amount of bytes in IDAT (including filter, padding and Adam7 bytes)
-amount of bytes in raw color model
Returns 1 if overflow possible, 0 if not.
*/
static int lodepng_pixel_overflow(unsigned w, unsigned h,
const LodePNGColorMode * pngcolor, const LodePNGColorMode * rawcolor)
{
size_t bpp = LODEPNG_MAX(lodepng_get_bpp(pngcolor), lodepng_get_bpp(rawcolor));
size_t numpixels, total;
size_t line; /* bytes per line in worst case */
if(lodepng_mulofl((size_t)w, (size_t)h, &numpixels)) return 1;
if(lodepng_mulofl(numpixels, 8, &total)) return 1; /* bit pointer with 8-bit color, or 8 bytes per channel color */
/* Bytes per scanline with the expression "(w / 8u) * bpp) + ((w & 7u) * bpp + 7u) / 8u" */
if(lodepng_mulofl((size_t)(w / 8u), bpp, &line)) return 1;
if(lodepng_addofl(line, ((w & 7u) * bpp + 7u) / 8u, &line)) return 1;
if(lodepng_addofl(line, 5, &line)) return 1; /* 5 bytes overhead per line: 1 filterbyte, 4 for Adam7 worst case */
if(lodepng_mulofl(line, h, &total)) return 1; /* Total bytes in worst case */
return 0; /* no overflow */
}
#endif /*LODEPNG_COMPILE_DECODER*/
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
static void LodePNGUnknownChunks_init(LodePNGInfo * info)
{
unsigned i;
for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0;
for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0;
}
static void LodePNGUnknownChunks_cleanup(LodePNGInfo * info)
{
unsigned i;
for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]);
}
static unsigned LodePNGUnknownChunks_copy(LodePNGInfo * dest, const LodePNGInfo * src)
{
unsigned i;
LodePNGUnknownChunks_cleanup(dest);
for(i = 0; i != 3; ++i) {
size_t j;
dest->unknown_chunks_size[i] = src->unknown_chunks_size[i];
dest->unknown_chunks_data[i] = (unsigned char *)lodepng_malloc(src->unknown_chunks_size[i]);
if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/
for(j = 0; j < src->unknown_chunks_size[i]; ++j) {
dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j];
}
}
return 0;
}
/******************************************************************************/
static void LodePNGText_init(LodePNGInfo * info)
{
info->text_num = 0;
info->text_keys = NULL;
info->text_strings = NULL;
}
static void LodePNGText_cleanup(LodePNGInfo * info)
{
size_t i;
for(i = 0; i != info->text_num; ++i) {
string_cleanup(&info->text_keys[i]);
string_cleanup(&info->text_strings[i]);
}
lodepng_free(info->text_keys);
lodepng_free(info->text_strings);
}
static unsigned LodePNGText_copy(LodePNGInfo * dest, const LodePNGInfo * source)
{
size_t i = 0;
dest->text_keys = NULL;
dest->text_strings = NULL;
dest->text_num = 0;
for(i = 0; i != source->text_num; ++i) {
CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i]));
}
return 0;
}
static unsigned lodepng_add_text_sized(LodePNGInfo * info, const char * key, const char * str, size_t size)
{
char ** new_keys = (char **)(lodepng_realloc(info->text_keys, sizeof(char *) * (info->text_num + 1)));
char ** new_strings = (char **)(lodepng_realloc(info->text_strings, sizeof(char *) * (info->text_num + 1)));
if(new_keys) info->text_keys = new_keys;
if(new_strings) info->text_strings = new_strings;
if(!new_keys || !new_strings) return 83; /*alloc fail*/
++info->text_num;
info->text_keys[info->text_num - 1] = alloc_string(key);
info->text_strings[info->text_num - 1] = alloc_string_sized(str, size);
if(!info->text_keys[info->text_num - 1] || !info->text_strings[info->text_num - 1]) return 83; /*alloc fail*/
return 0;
}
unsigned lodepng_add_text(LodePNGInfo * info, const char * key, const char * str)
{
return lodepng_add_text_sized(info, key, str, lodepng_strlen(str));
}
void lodepng_clear_text(LodePNGInfo * info)
{
LodePNGText_cleanup(info);
}
/******************************************************************************/
static void LodePNGIText_init(LodePNGInfo * info)
{
info->itext_num = 0;
info->itext_keys = NULL;
info->itext_langtags = NULL;
info->itext_transkeys = NULL;
info->itext_strings = NULL;
}
static void LodePNGIText_cleanup(LodePNGInfo * info)
{
size_t i;
for(i = 0; i != info->itext_num; ++i) {
string_cleanup(&info->itext_keys[i]);
string_cleanup(&info->itext_langtags[i]);
string_cleanup(&info->itext_transkeys[i]);
string_cleanup(&info->itext_strings[i]);
}
lodepng_free(info->itext_keys);
lodepng_free(info->itext_langtags);
lodepng_free(info->itext_transkeys);
lodepng_free(info->itext_strings);
}
static unsigned LodePNGIText_copy(LodePNGInfo * dest, const LodePNGInfo * source)
{
size_t i = 0;
dest->itext_keys = NULL;
dest->itext_langtags = NULL;
dest->itext_transkeys = NULL;
dest->itext_strings = NULL;
dest->itext_num = 0;
for(i = 0; i != source->itext_num; ++i) {
CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i],
source->itext_transkeys[i], source->itext_strings[i]));
}
return 0;
}
void lodepng_clear_itext(LodePNGInfo * info)
{
LodePNGIText_cleanup(info);
}
static unsigned lodepng_add_itext_sized(LodePNGInfo * info, const char * key, const char * langtag,
const char * transkey, const char * str, size_t size)
{
char ** new_keys = (char **)(lodepng_realloc(info->itext_keys, sizeof(char *) * (info->itext_num + 1)));
char ** new_langtags = (char **)(lodepng_realloc(info->itext_langtags, sizeof(char *) * (info->itext_num + 1)));
char ** new_transkeys = (char **)(lodepng_realloc(info->itext_transkeys, sizeof(char *) * (info->itext_num + 1)));
char ** new_strings = (char **)(lodepng_realloc(info->itext_strings, sizeof(char *) * (info->itext_num + 1)));
if(new_keys) info->itext_keys = new_keys;
if(new_langtags) info->itext_langtags = new_langtags;
if(new_transkeys) info->itext_transkeys = new_transkeys;
if(new_strings) info->itext_strings = new_strings;
if(!new_keys || !new_langtags || !new_transkeys || !new_strings) return 83; /*alloc fail*/
++info->itext_num;
info->itext_keys[info->itext_num - 1] = alloc_string(key);
info->itext_langtags[info->itext_num - 1] = alloc_string(langtag);
info->itext_transkeys[info->itext_num - 1] = alloc_string(transkey);
info->itext_strings[info->itext_num - 1] = alloc_string_sized(str, size);
return 0;
}
unsigned lodepng_add_itext(LodePNGInfo * info, const char * key, const char * langtag,
const char * transkey, const char * str)
{
return lodepng_add_itext_sized(info, key, langtag, transkey, str, lodepng_strlen(str));
}
/* same as set but does not delete */
static unsigned lodepng_assign_icc(LodePNGInfo * info, const char * name, const unsigned char * profile,
unsigned profile_size)
{
if(profile_size == 0) return 100; /*invalid ICC profile size*/
info->iccp_name = alloc_string(name);
info->iccp_profile = (unsigned char *)lodepng_malloc(profile_size);
if(!info->iccp_name || !info->iccp_profile) return 83; /*alloc fail*/
lodepng_memcpy(info->iccp_profile, profile, profile_size);
info->iccp_profile_size = profile_size;
return 0; /*ok*/
}
unsigned lodepng_set_icc(LodePNGInfo * info, const char * name, const unsigned char * profile, unsigned profile_size)
{
if(info->iccp_name) lodepng_clear_icc(info);
info->iccp_defined = 1;
return lodepng_assign_icc(info, name, profile, profile_size);
}
void lodepng_clear_icc(LodePNGInfo * info)
{
string_cleanup(&info->iccp_name);
lodepng_free(info->iccp_profile);
info->iccp_profile = NULL;
info->iccp_profile_size = 0;
info->iccp_defined = 0;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
void lodepng_info_init(LodePNGInfo * info)
{
lodepng_color_mode_init(&info->color);
info->interlace_method = 0;
info->compression_method = 0;
info->filter_method = 0;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
info->background_defined = 0;
info->background_r = info->background_g = info->background_b = 0;
LodePNGText_init(info);
LodePNGIText_init(info);
info->time_defined = 0;
info->phys_defined = 0;
info->gama_defined = 0;
info->chrm_defined = 0;
info->srgb_defined = 0;
info->iccp_defined = 0;
info->iccp_name = NULL;
info->iccp_profile = NULL;
LodePNGUnknownChunks_init(info);
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
void lodepng_info_cleanup(LodePNGInfo * info)
{
lodepng_color_mode_cleanup(&info->color);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
LodePNGText_cleanup(info);
LodePNGIText_cleanup(info);
lodepng_clear_icc(info);
LodePNGUnknownChunks_cleanup(info);
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
unsigned lodepng_info_copy(LodePNGInfo * dest, const LodePNGInfo * source)
{
lodepng_info_cleanup(dest);
lodepng_memcpy(dest, source, sizeof(LodePNGInfo));
lodepng_color_mode_init(&dest->color);
CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color));
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
CERROR_TRY_RETURN(LodePNGText_copy(dest, source));
CERROR_TRY_RETURN(LodePNGIText_copy(dest, source));
if(source->iccp_defined) {
CERROR_TRY_RETURN(lodepng_assign_icc(dest, source->iccp_name, source->iccp_profile, source->iccp_profile_size));
}
LodePNGUnknownChunks_init(dest);
CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source));
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
return 0;
}
/* ////////////////////////////////////////////////////////////////////////// */
/*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/
static void addColorBits(unsigned char * out, size_t index, unsigned bits, unsigned in)
{
unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/
/*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
unsigned p = index & m;
in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/
in = in << (bits * (m - p));
if(p == 0) out[index * bits / 8u] = in;
else out[index * bits / 8u] |= in;
}
typedef struct ColorTree ColorTree;
/*
One node of a color tree
This is the data structure used to count the number of unique colors and to get a palette
index for a color. It's like an octree, but because the alpha channel is used too, each
node has 16 instead of 8 children.
*/
struct ColorTree {
ColorTree * children[16]; /*up to 16 pointers to ColorTree of next level*/
int index; /*the payload. Only has a meaningful value if this is in the last level*/
};
static void color_tree_init(ColorTree * tree)
{
lodepng_memset(tree->children, 0, 16 * sizeof(*tree->children));
tree->index = -1;
}
static void color_tree_cleanup(ColorTree * tree)
{
int i;
for(i = 0; i != 16; ++i) {
if(tree->children[i]) {
color_tree_cleanup(tree->children[i]);
lodepng_free(tree->children[i]);
}
}
}
/*returns -1 if color not present, its index otherwise*/
static int color_tree_get(ColorTree * tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
{
int bit = 0;
for(bit = 0; bit < 8; ++bit) {
int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
if(!tree->children[i]) return -1;
else tree = tree->children[i];
}
return tree ? tree->index : -1;
}
#ifdef LODEPNG_COMPILE_ENCODER
static int color_tree_has(ColorTree * tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
{
return color_tree_get(tree, r, g, b, a) >= 0;
}
#endif /*LODEPNG_COMPILE_ENCODER*/
/*color is not allowed to already exist.
Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")
Returns error code, or 0 if ok*/
static unsigned color_tree_add(ColorTree * tree,
unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index)
{
int bit;
for(bit = 0; bit < 8; ++bit) {
int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
if(!tree->children[i]) {
tree->children[i] = (ColorTree *)lodepng_malloc(sizeof(ColorTree));
if(!tree->children[i]) return 83; /*alloc fail*/
color_tree_init(tree->children[i]);
}
tree = tree->children[i];
}
tree->index = (int)index;
return 0;
}
/*put a pixel, given its RGBA color, into image of any color type*/
static unsigned rgba8ToPixel(unsigned char * out, size_t i,
const LodePNGColorMode * mode, ColorTree * tree /*for palette*/,
unsigned char r, unsigned char g, unsigned char b, unsigned char a)
{
if(mode->colortype == LCT_GREY) {
unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/
if(mode->bitdepth == 8) out[i] = gray;
else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = gray;
else {
/*take the most significant bits of gray*/
gray = ((unsigned)gray >> (8u - mode->bitdepth)) & ((1u << mode->bitdepth) - 1u);
addColorBits(out, i, mode->bitdepth, gray);
}
}
else if(mode->colortype == LCT_RGB) {
if(mode->bitdepth == 8) {
out[i * 3 + 0] = r;
out[i * 3 + 1] = g;
out[i * 3 + 2] = b;
}
else {
out[i * 6 + 0] = out[i * 6 + 1] = r;
out[i * 6 + 2] = out[i * 6 + 3] = g;
out[i * 6 + 4] = out[i * 6 + 5] = b;
}
}
else if(mode->colortype == LCT_PALETTE) {
int index = color_tree_get(tree, r, g, b, a);
if(index < 0) return 82; /*color not in palette*/
if(mode->bitdepth == 8) out[i] = index;
else addColorBits(out, i, mode->bitdepth, (unsigned)index);
}
else if(mode->colortype == LCT_GREY_ALPHA) {
unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/
if(mode->bitdepth == 8) {
out[i * 2 + 0] = gray;
out[i * 2 + 1] = a;
}
else if(mode->bitdepth == 16) {
out[i * 4 + 0] = out[i * 4 + 1] = gray;
out[i * 4 + 2] = out[i * 4 + 3] = a;
}
}
else if(mode->colortype == LCT_RGBA) {
if(mode->bitdepth == 8) {
out[i * 4 + 0] = r;
out[i * 4 + 1] = g;
out[i * 4 + 2] = b;
out[i * 4 + 3] = a;
}
else {
out[i * 8 + 0] = out[i * 8 + 1] = r;
out[i * 8 + 2] = out[i * 8 + 3] = g;
out[i * 8 + 4] = out[i * 8 + 5] = b;
out[i * 8 + 6] = out[i * 8 + 7] = a;
}
}
return 0; /*no error*/
}
/*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/
static void rgba16ToPixel(unsigned char * out, size_t i,
const LodePNGColorMode * mode,
unsigned short r, unsigned short g, unsigned short b, unsigned short a)
{
if(mode->colortype == LCT_GREY) {
unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/
out[i * 2 + 0] = (gray >> 8) & 255;
out[i * 2 + 1] = gray & 255;
}
else if(mode->colortype == LCT_RGB) {
out[i * 6 + 0] = (r >> 8) & 255;
out[i * 6 + 1] = r & 255;
out[i * 6 + 2] = (g >> 8) & 255;
out[i * 6 + 3] = g & 255;
out[i * 6 + 4] = (b >> 8) & 255;
out[i * 6 + 5] = b & 255;
}
else if(mode->colortype == LCT_GREY_ALPHA) {
unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/
out[i * 4 + 0] = (gray >> 8) & 255;
out[i * 4 + 1] = gray & 255;
out[i * 4 + 2] = (a >> 8) & 255;
out[i * 4 + 3] = a & 255;
}
else if(mode->colortype == LCT_RGBA) {
out[i * 8 + 0] = (r >> 8) & 255;
out[i * 8 + 1] = r & 255;
out[i * 8 + 2] = (g >> 8) & 255;
out[i * 8 + 3] = g & 255;
out[i * 8 + 4] = (b >> 8) & 255;
out[i * 8 + 5] = b & 255;
out[i * 8 + 6] = (a >> 8) & 255;
out[i * 8 + 7] = a & 255;
}
}
/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
static void getPixelColorRGBA8(unsigned char * r, unsigned char * g,
unsigned char * b, unsigned char * a,
const unsigned char * in, size_t i,
const LodePNGColorMode * mode)
{
if(mode->colortype == LCT_GREY) {
if(mode->bitdepth == 8) {
*r = *g = *b = in[i];
if(mode->key_defined && *r == mode->key_r) *a = 0;
else *a = 255;
}
else if(mode->bitdepth == 16) {
*r = *g = *b = in[i * 2 + 0];
if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
else *a = 255;
}
else {
unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
size_t j = i * mode->bitdepth;
unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
*r = *g = *b = (value * 255) / highest;
if(mode->key_defined && value == mode->key_r) *a = 0;
else *a = 255;
}
}
else if(mode->colortype == LCT_RGB) {
if(mode->bitdepth == 8) {
*r = in[i * 3 + 0];
*g = in[i * 3 + 1];
*b = in[i * 3 + 2];
if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0;
else *a = 255;
}
else {
*r = in[i * 6 + 0];
*g = in[i * 6 + 2];
*b = in[i * 6 + 4];
if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
&& 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
&& 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
else *a = 255;
}
}
else if(mode->colortype == LCT_PALETTE) {
unsigned index;
if(mode->bitdepth == 8) index = in[i];
else {
size_t j = i * mode->bitdepth;
index = readBitsFromReversedStream(&j, in, mode->bitdepth);
}
/*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
*r = mode->palette[index * 4 + 0];
*g = mode->palette[index * 4 + 1];
*b = mode->palette[index * 4 + 2];
*a = mode->palette[index * 4 + 3];
}
else if(mode->colortype == LCT_GREY_ALPHA) {
if(mode->bitdepth == 8) {
*r = *g = *b = in[i * 2 + 0];
*a = in[i * 2 + 1];
}
else {
*r = *g = *b = in[i * 4 + 0];
*a = in[i * 4 + 2];
}
}
else if(mode->colortype == LCT_RGBA) {
if(mode->bitdepth == 8) {
*r = in[i * 4 + 0];
*g = in[i * 4 + 1];
*b = in[i * 4 + 2];
*a = in[i * 4 + 3];
}
else {
*r = in[i * 8 + 0];
*g = in[i * 8 + 2];
*b = in[i * 8 + 4];
*a = in[i * 8 + 6];
}
}
}
/*Similar to getPixelColorRGBA8, but with all the for loops inside of the color
mode test cases, optimized to convert the colors much faster, when converting
to the common case of RGBA with 8 bit per channel. buffer must be RGBA with
enough memory.*/
static void getPixelColorsRGBA8(unsigned char * LODEPNG_RESTRICT buffer, size_t numpixels,
const unsigned char * LODEPNG_RESTRICT in,
const LodePNGColorMode * mode)
{
unsigned num_channels = 4;
size_t i;
if(mode->colortype == LCT_GREY) {
if(mode->bitdepth == 8) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = buffer[1] = buffer[2] = in[i];
buffer[3] = 255;
}
if(mode->key_defined) {
buffer -= numpixels * num_channels;
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
if(buffer[0] == mode->key_r) buffer[3] = 0;
}
}
}
else if(mode->bitdepth == 16) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = buffer[1] = buffer[2] = in[i * 2];
buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255;
}
}
else {
unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
size_t j = 0;
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255;
}
}
}
else if(mode->colortype == LCT_RGB) {
if(mode->bitdepth == 8) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
lodepng_memcpy(buffer, &in[i * 3], 3);
buffer[3] = 255;
}
if(mode->key_defined) {
buffer -= numpixels * num_channels;
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
if(buffer[0] == mode->key_r && buffer[1] == mode->key_g && buffer[2] == mode->key_b) buffer[3] = 0;
}
}
}
else {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = in[i * 6 + 0];
buffer[1] = in[i * 6 + 2];
buffer[2] = in[i * 6 + 4];
buffer[3] = mode->key_defined
&& 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
&& 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
&& 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255;
}
}
}
else if(mode->colortype == LCT_PALETTE) {
if(mode->bitdepth == 8) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
unsigned index = in[i];
/*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
lodepng_memcpy(buffer, &mode->palette[index * 4], 4);
}
}
else {
size_t j = 0;
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth);
/*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
lodepng_memcpy(buffer, &mode->palette[index * 4], 4);
}
}
}
else if(mode->colortype == LCT_GREY_ALPHA) {
if(mode->bitdepth == 8) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
buffer[3] = in[i * 2 + 1];
}
}
else {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
buffer[3] = in[i * 4 + 2];
}
}
}
else if(mode->colortype == LCT_RGBA) {
if(mode->bitdepth == 8) {
lodepng_memcpy(buffer, in, numpixels * 4);
}
else {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = in[i * 8 + 0];
buffer[1] = in[i * 8 + 2];
buffer[2] = in[i * 8 + 4];
buffer[3] = in[i * 8 + 6];
}
}
}
}
/*Similar to getPixelColorsRGBA8, but with 3-channel RGB output.*/
static void getPixelColorsRGB8(unsigned char * LODEPNG_RESTRICT buffer, size_t numpixels,
const unsigned char * LODEPNG_RESTRICT in,
const LodePNGColorMode * mode)
{
const unsigned num_channels = 3;
size_t i;
if(mode->colortype == LCT_GREY) {
if(mode->bitdepth == 8) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = buffer[1] = buffer[2] = in[i];
}
}
else if(mode->bitdepth == 16) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = buffer[1] = buffer[2] = in[i * 2];
}
}
else {
unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
size_t j = 0;
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
}
}
}
else if(mode->colortype == LCT_RGB) {
if(mode->bitdepth == 8) {
lodepng_memcpy(buffer, in, numpixels * 3);
}
else {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = in[i * 6 + 0];
buffer[1] = in[i * 6 + 2];
buffer[2] = in[i * 6 + 4];
}
}
}
else if(mode->colortype == LCT_PALETTE) {
if(mode->bitdepth == 8) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
unsigned index = in[i];
/*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
lodepng_memcpy(buffer, &mode->palette[index * 4], 3);
}
}
else {
size_t j = 0;
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth);
/*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
lodepng_memcpy(buffer, &mode->palette[index * 4], 3);
}
}
}
else if(mode->colortype == LCT_GREY_ALPHA) {
if(mode->bitdepth == 8) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
}
}
else {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
}
}
}
else if(mode->colortype == LCT_RGBA) {
if(mode->bitdepth == 8) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
lodepng_memcpy(buffer, &in[i * 4], 3);
}
}
else {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = in[i * 8 + 0];
buffer[1] = in[i * 8 + 2];
buffer[2] = in[i * 8 + 4];
}
}
}
}
/*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
given color type, but the given color type must be 16-bit itself.*/
static void getPixelColorRGBA16(unsigned short * r, unsigned short * g, unsigned short * b, unsigned short * a,
const unsigned char * in, size_t i, const LodePNGColorMode * mode)
{
if(mode->colortype == LCT_GREY) {
*r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1];
if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
else *a = 65535;
}
else if(mode->colortype == LCT_RGB) {
*r = 256u * in[i * 6 + 0] + in[i * 6 + 1];
*g = 256u * in[i * 6 + 2] + in[i * 6 + 3];
*b = 256u * in[i * 6 + 4] + in[i * 6 + 5];
if(mode->key_defined
&& 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
&& 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
&& 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
else *a = 65535;
}
else if(mode->colortype == LCT_GREY_ALPHA) {
*r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1];
*a = 256u * in[i * 4 + 2] + in[i * 4 + 3];
}
else if(mode->colortype == LCT_RGBA) {
*r = 256u * in[i * 8 + 0] + in[i * 8 + 1];
*g = 256u * in[i * 8 + 2] + in[i * 8 + 3];
*b = 256u * in[i * 8 + 4] + in[i * 8 + 5];
*a = 256u * in[i * 8 + 6] + in[i * 8 + 7];
}
}
unsigned lodepng_convert(unsigned char * out, const unsigned char * in,
const LodePNGColorMode * mode_out, const LodePNGColorMode * mode_in,
unsigned w, unsigned h)
{
size_t i;
ColorTree tree;
size_t numpixels = (size_t)w * (size_t)h;
unsigned error = 0;
if(mode_in->colortype == LCT_PALETTE && !mode_in->palette) {
return 107; /* error: must provide palette if input mode is palette */
}
if(lodepng_color_mode_equal(mode_out, mode_in)) {
size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
lodepng_memcpy(out, in, numbytes);
return 0;
}
if(mode_out->colortype == LCT_PALETTE) {
size_t palettesize = mode_out->palettesize;
const unsigned char * palette = mode_out->palette;
size_t palsize = (size_t)1u << mode_out->bitdepth;
/*if the user specified output palette but did not give the values, assume
they want the values of the input color type (assuming that one is palette).
Note that we never create a new palette ourselves.*/
if(palettesize == 0) {
palettesize = mode_in->palettesize;
palette = mode_in->palette;
/*if the input was also palette with same bitdepth, then the color types are also
equal, so copy literally. This to preserve the exact indices that were in the PNG
even in case there are duplicate colors in the palette.*/
if(mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) {
size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
lodepng_memcpy(out, in, numbytes);
return 0;
}
}
if(palettesize < palsize) palsize = palettesize;
color_tree_init(&tree);
for(i = 0; i != palsize; ++i) {
const unsigned char * p = &palette[i * 4];
error = color_tree_add(&tree, p[0], p[1], p[2], p[3], (unsigned)i);
if(error) break;
}
}
if(!error) {
if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) {
for(i = 0; i != numpixels; ++i) {
unsigned short r = 0, g = 0, b = 0, a = 0;
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
rgba16ToPixel(out, i, mode_out, r, g, b, a);
}
}
else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) {
getPixelColorsRGBA8(out, numpixels, in, mode_in);
}
else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) {
getPixelColorsRGB8(out, numpixels, in, mode_in);
}
else {
unsigned char r = 0, g = 0, b = 0, a = 0;
for(i = 0; i != numpixels; ++i) {
getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a);
if(error) break;
}
}
}
if(mode_out->colortype == LCT_PALETTE) {
color_tree_cleanup(&tree);
}
return error;
}
/* Converts a single rgb color without alpha from one type to another, color bits truncated to
their bitdepth. In case of single channel (gray or palette), only the r channel is used. Slow
function, do not use to process all pixels of an image. Alpha channel not supported on purpose:
this is for bKGD, supporting alpha may prevent it from finding a color in the palette, from the
specification it looks like bKGD should ignore the alpha values of the palette since it can use
any palette index but doesn't have an alpha channel. Idem with ignoring color key. */
static unsigned lodepng_convert_rgb(
unsigned * r_out, unsigned * g_out, unsigned * b_out,
unsigned r_in, unsigned g_in, unsigned b_in,
const LodePNGColorMode * mode_out, const LodePNGColorMode * mode_in)
{
unsigned r = 0, g = 0, b = 0;
unsigned mul = 65535 / ((1u << mode_in->bitdepth) - 1u); /*65535, 21845, 4369, 257, 1*/
unsigned shift = 16 - mode_out->bitdepth;
if(mode_in->colortype == LCT_GREY || mode_in->colortype == LCT_GREY_ALPHA) {
r = g = b = r_in * mul;
}
else if(mode_in->colortype == LCT_RGB || mode_in->colortype == LCT_RGBA) {
r = r_in * mul;
g = g_in * mul;
b = b_in * mul;
}
else if(mode_in->colortype == LCT_PALETTE) {
if(r_in >= mode_in->palettesize) return 82;
r = mode_in->palette[r_in * 4 + 0] * 257u;
g = mode_in->palette[r_in * 4 + 1] * 257u;
b = mode_in->palette[r_in * 4 + 2] * 257u;
}
else {
return 31;
}
/* now convert to output format */
if(mode_out->colortype == LCT_GREY || mode_out->colortype == LCT_GREY_ALPHA) {
*r_out = r >> shift ;
}
else if(mode_out->colortype == LCT_RGB || mode_out->colortype == LCT_RGBA) {
*r_out = r >> shift ;
*g_out = g >> shift ;
*b_out = b >> shift ;
}
else if(mode_out->colortype == LCT_PALETTE) {
unsigned i;
/* a 16-bit color cannot be in the palette */
if((r >> 8) != (r & 255) || (g >> 8) != (g & 255) || (b >> 8) != (b & 255)) return 82;
for(i = 0; i < mode_out->palettesize; i++) {
unsigned j = i * 4;
if((r >> 8) == mode_out->palette[j + 0] && (g >> 8) == mode_out->palette[j + 1] &&
(b >> 8) == mode_out->palette[j + 2]) {
*r_out = i;
return 0;
}
}
return 82;
}
else {
return 31;
}
return 0;
}
#ifdef LODEPNG_COMPILE_ENCODER
void lodepng_color_stats_init(LodePNGColorStats * stats)
{
/*stats*/
stats->colored = 0;
stats->key = 0;
stats->key_r = stats->key_g = stats->key_b = 0;
stats->alpha = 0;
stats->numcolors = 0;
stats->bits = 1;
stats->numpixels = 0;
/*settings*/
stats->allow_palette = 1;
stats->allow_greyscale = 1;
}
/*function used for debug purposes with C++*/
/*void printColorStats(LodePNGColorStats* p) {
std::cout << "colored: " << (int)p->colored << ", ";
std::cout << "key: " << (int)p->key << ", ";
std::cout << "key_r: " << (int)p->key_r << ", ";
std::cout << "key_g: " << (int)p->key_g << ", ";
std::cout << "key_b: " << (int)p->key_b << ", ";
std::cout << "alpha: " << (int)p->alpha << ", ";
std::cout << "numcolors: " << (int)p->numcolors << ", ";
std::cout << "bits: " << (int)p->bits << std::endl;
}*/
/*Returns how many bits needed to represent given value (max 8 bit)*/
static unsigned getValueRequiredBits(unsigned char value)
{
if(value == 0 || value == 255) return 1;
/*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/
if(value % 17 == 0) return value % 85 == 0 ? 2 : 4;
return 8;
}
/*stats must already have been inited. */
unsigned lodepng_compute_color_stats(LodePNGColorStats * stats,
const unsigned char * in, unsigned w, unsigned h,
const LodePNGColorMode * mode_in)
{
size_t i;
ColorTree tree;
size_t numpixels = (size_t)w * (size_t)h;
unsigned error = 0;
/* mark things as done already if it would be impossible to have a more expensive case */
unsigned colored_done = lodepng_is_greyscale_type(mode_in) ? 1 : 0;
unsigned alpha_done = lodepng_can_have_alpha(mode_in) ? 0 : 1;
unsigned numcolors_done = 0;
unsigned bpp = lodepng_get_bpp(mode_in);
unsigned bits_done = (stats->bits == 1 && bpp == 1) ? 1 : 0;
unsigned sixteen = 0; /* whether the input image is 16 bit */
unsigned maxnumcolors = 257;
if(bpp <= 8) maxnumcolors = LODEPNG_MIN(257, stats->numcolors + (1u << bpp));
stats->numpixels += numpixels;
/*if palette not allowed, no need to compute numcolors*/
if(!stats->allow_palette) numcolors_done = 1;
color_tree_init(&tree);
/*If the stats was already filled in from previous data, fill its palette in tree
and mark things as done already if we know they are the most expensive case already*/
if(stats->alpha) alpha_done = 1;
if(stats->colored) colored_done = 1;
if(stats->bits == 16) numcolors_done = 1;
if(stats->bits >= bpp) bits_done = 1;
if(stats->numcolors >= maxnumcolors) numcolors_done = 1;
if(!numcolors_done) {
for(i = 0; i < stats->numcolors; i++) {
const unsigned char * color = &stats->palette[i * 4];
error = color_tree_add(&tree, color[0], color[1], color[2], color[3], i);
if(error) goto cleanup;
}
}
/*Check if the 16-bit input is truly 16-bit*/
if(mode_in->bitdepth == 16 && !sixteen) {
unsigned short r = 0, g = 0, b = 0, a = 0;
for(i = 0; i != numpixels; ++i) {
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) ||
(b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) { /*first and second byte differ*/
stats->bits = 16;
sixteen = 1;
bits_done = 1;
numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
break;
}
}
}
if(sixteen) {
unsigned short r = 0, g = 0, b = 0, a = 0;
for(i = 0; i != numpixels; ++i) {
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
if(!colored_done && (r != g || r != b)) {
stats->colored = 1;
colored_done = 1;
}
if(!alpha_done) {
unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b);
if(a != 65535 && (a != 0 || (stats->key && !matchkey))) {
stats->alpha = 1;
stats->key = 0;
alpha_done = 1;
}
else if(a == 0 && !stats->alpha && !stats->key) {
stats->key = 1;
stats->key_r = r;
stats->key_g = g;
stats->key_b = b;
}
else if(a == 65535 && stats->key && matchkey) {
/* Color key cannot be used if an opaque pixel also has that RGB color. */
stats->alpha = 1;
stats->key = 0;
alpha_done = 1;
}
}
if(alpha_done && numcolors_done && colored_done && bits_done) break;
}
if(stats->key && !stats->alpha) {
for(i = 0; i != numpixels; ++i) {
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) {
/* Color key cannot be used if an opaque pixel also has that RGB color. */
stats->alpha = 1;
stats->key = 0;
alpha_done = 1;
}
}
}
}
else { /* < 16-bit */
unsigned char r = 0, g = 0, b = 0, a = 0;
for(i = 0; i != numpixels; ++i) {
getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
if(!bits_done && stats->bits < 8) {
/*only r is checked, < 8 bits is only relevant for grayscale*/
unsigned bits = getValueRequiredBits(r);
if(bits > stats->bits) stats->bits = bits;
}
bits_done = (stats->bits >= bpp);
if(!colored_done && (r != g || r != b)) {
stats->colored = 1;
colored_done = 1;
if(stats->bits < 8) stats->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/
}
if(!alpha_done) {
unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b);
if(a != 255 && (a != 0 || (stats->key && !matchkey))) {
stats->alpha = 1;
stats->key = 0;
alpha_done = 1;
if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
}
else if(a == 0 && !stats->alpha && !stats->key) {
stats->key = 1;
stats->key_r = r;
stats->key_g = g;
stats->key_b = b;
}
else if(a == 255 && stats->key && matchkey) {
/* Color key cannot be used if an opaque pixel also has that RGB color. */
stats->alpha = 1;
stats->key = 0;
alpha_done = 1;
if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
}
}
if(!numcolors_done) {
if(!color_tree_has(&tree, r, g, b, a)) {
error = color_tree_add(&tree, r, g, b, a, stats->numcolors);
if(error) goto cleanup;
if(stats->numcolors < 256) {
unsigned char * p = stats->palette;
unsigned n = stats->numcolors;
p[n * 4 + 0] = r;
p[n * 4 + 1] = g;
p[n * 4 + 2] = b;
p[n * 4 + 3] = a;
}
++stats->numcolors;
numcolors_done = stats->numcolors >= maxnumcolors;
}
}
if(alpha_done && numcolors_done && colored_done && bits_done) break;
}
if(stats->key && !stats->alpha) {
for(i = 0; i != numpixels; ++i) {
getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) {
/* Color key cannot be used if an opaque pixel also has that RGB color. */
stats->alpha = 1;
stats->key = 0;
alpha_done = 1;
if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
}
}
}
/*make the stats's key always 16-bit for consistency - repeat each byte twice*/
stats->key_r += (stats->key_r << 8);
stats->key_g += (stats->key_g << 8);
stats->key_b += (stats->key_b << 8);
}
cleanup:
color_tree_cleanup(&tree);
return error;
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*Adds a single color to the color stats. The stats must already have been inited. The color must be given as 16-bit
(with 2 bytes repeating for 8-bit and 65535 for opaque alpha channel). This function is expensive, do not call it for
all pixels of an image but only for a few additional values. */
static unsigned lodepng_color_stats_add(LodePNGColorStats * stats,
unsigned r, unsigned g, unsigned b, unsigned a)
{
unsigned error = 0;
unsigned char image[8];
LodePNGColorMode mode;
lodepng_color_mode_init(&mode);
image[0] = r >> 8;
image[1] = r;
image[2] = g >> 8;
image[3] = g;
image[4] = b >> 8;
image[5] = b;
image[6] = a >> 8;
image[7] = a;
mode.bitdepth = 16;
mode.colortype = LCT_RGBA;
error = lodepng_compute_color_stats(stats, image, 1, 1, &mode);
lodepng_color_mode_cleanup(&mode);
return error;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*Computes a minimal PNG color model that can contain all colors as indicated by the stats.
The stats should be computed with lodepng_compute_color_stats.
mode_in is raw color profile of the image the stats were computed on, to copy palette order from when relevant.
Minimal PNG color model means the color type and bit depth that gives smallest amount of bits in the output image,
e.g. gray if only grayscale pixels, palette if less than 256 colors, color key if only single transparent color, ...
This is used if auto_convert is enabled (it is by default).
*/
static unsigned auto_choose_color(LodePNGColorMode * mode_out,
const LodePNGColorMode * mode_in,
const LodePNGColorStats * stats)
{
unsigned error = 0;
unsigned palettebits;
size_t i, n;
size_t numpixels = stats->numpixels;
unsigned palette_ok, gray_ok;
unsigned alpha = stats->alpha;
unsigned key = stats->key;
unsigned bits = stats->bits;
mode_out->key_defined = 0;
if(key && numpixels <= 16) {
alpha = 1; /*too few pixels to justify tRNS chunk overhead*/
key = 0;
if(bits < 8) bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
}
gray_ok = !stats->colored;
if(!stats->allow_greyscale) gray_ok = 0;
if(!gray_ok && bits < 8) bits = 8;
n = stats->numcolors;
palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8));
palette_ok = n <= 256 && bits <= 8 && n != 0; /*n==0 means likely numcolors wasn't computed*/
if(numpixels < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/
if(gray_ok && !alpha && bits <= palettebits) palette_ok = 0; /*gray is less overhead*/
if(!stats->allow_palette) palette_ok = 0;
if(palette_ok) {
const unsigned char * p = stats->palette;
lodepng_palette_clear(mode_out); /*remove potential earlier palette*/
for(i = 0; i != stats->numcolors; ++i) {
error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]);
if(error) break;
}
mode_out->colortype = LCT_PALETTE;
mode_out->bitdepth = palettebits;
if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize
&& mode_in->bitdepth == mode_out->bitdepth) {
/*If input should have same palette colors, keep original to preserve its order and prevent conversion*/
lodepng_color_mode_cleanup(mode_out);
lodepng_color_mode_copy(mode_out, mode_in);
}
}
else { /*8-bit or 16-bit per channel*/
mode_out->bitdepth = bits;
mode_out->colortype = alpha ? (gray_ok ? LCT_GREY_ALPHA : LCT_RGBA)
: (gray_ok ? LCT_GREY : LCT_RGB);
if(key) {
unsigned mask = (1u << mode_out->bitdepth) - 1u; /*stats always uses 16-bit, mask converts it*/
mode_out->key_r = stats->key_r & mask;
mode_out->key_g = stats->key_g & mask;
mode_out->key_b = stats->key_b & mask;
mode_out->key_defined = 1;
}
}
return error;
}
#endif /* #ifdef LODEPNG_COMPILE_ENCODER */
/*
Paeth predictor, used by PNG filter type 4
The parameters are of type short, but should come from unsigned chars, the shorts
are only needed to make the paeth calculation correct.
*/
static unsigned char paethPredictor(short a, short b, short c)
{
short pa = LODEPNG_ABS(b - c);
short pb = LODEPNG_ABS(a - c);
short pc = LODEPNG_ABS(a + b - c - c);
/* return input value associated with smallest of pa, pb, pc (with certain priority if equal) */
if(pb < pa) {
a = b;
pa = pb;
}
return (pc < pa) ? c : a;
}
/*shared values used by multiple Adam7 related functions*/
static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
/*
Outputs various dimensions and positions in the image related to the Adam7 reduced images.
passw: output containing the width of the 7 passes
passh: output containing the height of the 7 passes
filter_passstart: output containing the index of the start and end of each
reduced image with filter bytes
padded_passstart output containing the index of the start and end of each
reduced image when without filter bytes but with padded scanlines
passstart: output containing the index of the start and end of each reduced
image without padding between scanlines, but still padding between the images
w, h: width and height of non-interlaced image
bpp: bits per pixel
"padded" is only relevant if bpp is less than 8 and a scanline or image does not
end at a full byte
*/
static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8],
size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp)
{
/*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/
unsigned i;
/*calculate width and height in pixels of each pass*/
for(i = 0; i != 7; ++i) {
passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i];
passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i];
if(passw[i] == 0) passh[i] = 0;
if(passh[i] == 0) passw[i] = 0;
}
filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;
for(i = 0; i != 7; ++i) {
/*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/
filter_passstart[i + 1] = filter_passstart[i]
+ ((passw[i] && passh[i]) ? passh[i] * (1u + (passw[i] * bpp + 7u) / 8u) : 0);
/*bits padded if needed to fill full byte at end of each scanline*/
padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7u) / 8u);
/*only padded at end of reduced image*/
passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7u) / 8u;
}
}
#ifdef LODEPNG_COMPILE_DECODER
/* ////////////////////////////////////////////////////////////////////////// */
/* / PNG Decoder / */
/* ////////////////////////////////////////////////////////////////////////// */
/*read the information from the header and store it in the LodePNGInfo. return value is error*/
unsigned lodepng_inspect(unsigned * w, unsigned * h, LodePNGState * state,
const unsigned char * in, size_t insize)
{
unsigned width, height;
LodePNGInfo * info = &state->info_png;
if(insize == 0 || in == 0) {
CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/
}
if(insize < 33) {
CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/
}
/*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
/* TODO: remove this. One should use a new LodePNGState for new sessions */
lodepng_info_cleanup(info);
lodepng_info_init(info);
if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71
|| in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) {
CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/
}
if(lodepng_chunk_length(in + 8) != 13) {
CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/
}
if(!lodepng_chunk_type_equals(in + 8, "IHDR")) {
CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/
}
/*read the values given in the header*/
width = lodepng_read32bitInt(&in[16]);
height = lodepng_read32bitInt(&in[20]);
/*TODO: remove the undocumented feature that allows to give null pointers to width or height*/
if(w) *w = width;
if(h) *h = height;
info->color.bitdepth = in[24];
info->color.colortype = (LodePNGColorType)in[25];
info->compression_method = in[26];
info->filter_method = in[27];
info->interlace_method = in[28];
/*errors returned only after the parsing so other values are still output*/
/*error: invalid image size*/
if(width == 0 || height == 0) CERROR_RETURN_ERROR(state->error, 93);
/*error: invalid colortype or bitdepth combination*/
state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);
if(state->error) return state->error;
/*error: only compression method 0 is allowed in the specification*/
if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);
/*error: only filter method 0 is allowed in the specification*/
if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);
/*error: only interlace methods 0 and 1 exist in the specification*/
if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);
if(!state->decoder.ignore_crc) {
unsigned CRC = lodepng_read32bitInt(&in[29]);
unsigned checksum = lodepng_crc32(&in[12], 17);
if(CRC != checksum) {
CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/
}
}
return state->error;
}
static unsigned unfilterScanline(unsigned char * recon, const unsigned char * scanline, const unsigned char * precon,
size_t bytewidth, unsigned char filterType, size_t length)
{
/*
For PNG filter method 0
unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
the filter works byte per byte (bytewidth = 1)
precon is the previous unfiltered scanline, recon the result, scanline the current one
the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
recon and scanline MAY be the same memory address! precon must be disjoint.
*/
size_t i;
switch(filterType) {
case 0:
for(i = 0; i != length; ++i) recon[i] = scanline[i];
break;
case 1:
for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth];
break;
case 2:
if(precon) {
for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i];
}
else {
for(i = 0; i != length; ++i) recon[i] = scanline[i];
}
break;
case 3:
if(precon) {
for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1u);
for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) >> 1u);
}
else {
for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + (recon[i - bytewidth] >> 1u);
}
break;
case 4:
if(precon) {
for(i = 0; i != bytewidth; ++i) {
recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
}
/* Unroll independent paths of the paeth predictor. A 6x and 8x version would also be possible but that
adds too much code. Whether this actually speeds anything up at all depends on compiler and settings. */
if(bytewidth >= 4) {
for(; i + 3 < length; i += 4) {
size_t j = i - bytewidth;
unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2], s3 = scanline[i + 3];
unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2], r3 = recon[j + 3];
unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2], p3 = precon[i + 3];
unsigned char q0 = precon[j + 0], q1 = precon[j + 1], q2 = precon[j + 2], q3 = precon[j + 3];
recon[i + 0] = s0 + paethPredictor(r0, p0, q0);
recon[i + 1] = s1 + paethPredictor(r1, p1, q1);
recon[i + 2] = s2 + paethPredictor(r2, p2, q2);
recon[i + 3] = s3 + paethPredictor(r3, p3, q3);
}
}
else if(bytewidth >= 3) {
for(; i + 2 < length; i += 3) {
size_t j = i - bytewidth;
unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2];
unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2];
unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2];
unsigned char q0 = precon[j + 0], q1 = precon[j + 1], q2 = precon[j + 2];
recon[i + 0] = s0 + paethPredictor(r0, p0, q0);
recon[i + 1] = s1 + paethPredictor(r1, p1, q1);
recon[i + 2] = s2 + paethPredictor(r2, p2, q2);
}
}
else if(bytewidth >= 2) {
for(; i + 1 < length; i += 2) {
size_t j = i - bytewidth;
unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1];
unsigned char r0 = recon[j + 0], r1 = recon[j + 1];
unsigned char p0 = precon[i + 0], p1 = precon[i + 1];
unsigned char q0 = precon[j + 0], q1 = precon[j + 1];
recon[i + 0] = s0 + paethPredictor(r0, p0, q0);
recon[i + 1] = s1 + paethPredictor(r1, p1, q1);
}
}
for(; i != length; ++i) {
recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));
}
}
else {
for(i = 0; i != bytewidth; ++i) {
recon[i] = scanline[i];
}
for(i = bytewidth; i < length; ++i) {
/*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/
recon[i] = (scanline[i] + recon[i - bytewidth]);
}
}
break;
default:
return 36; /*error: invalid filter type given*/
}
return 0;
}
static unsigned unfilter(unsigned char * out, const unsigned char * in, unsigned w, unsigned h, unsigned bpp)
{
/*
For PNG filter method 0
this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
*/
unsigned y;
unsigned char * prevline = 0;
/*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
size_t bytewidth = (bpp + 7u) / 8u;
/*the width of a scanline in bytes, not including the filter type*/
size_t linebytes = lodepng_get_raw_size_idat(w, 1, bpp) - 1u;
for(y = 0; y < h; ++y) {
size_t outindex = linebytes * y;
size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
unsigned char filterType = in[inindex];
CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));
prevline = &out[outindex];
}
return 0;
}
/*
in: Adam7 interlaced image, with no padding bits between scanlines, but between
reduced images so that each reduced image starts at a byte.
out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
bpp: bits per pixel
out has the following size in bits: w * h * bpp.
in is possibly bigger due to padding bits between reduced images.
out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
(because that's likely a little bit faster)
NOTE: comments about padding bits are only relevant if bpp < 8
*/
static void Adam7_deinterlace(unsigned char * out, const unsigned char * in, unsigned w, unsigned h, unsigned bpp)
{
unsigned passw[7], passh[7];
size_t filter_passstart[8], padded_passstart[8], passstart[8];
unsigned i;
Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
if(bpp >= 8) {
for(i = 0; i != 7; ++i) {
unsigned x, y, b;
size_t bytewidth = bpp / 8u;
for(y = 0; y < passh[i]; ++y)
for(x = 0; x < passw[i]; ++x) {
size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth;
size_t pixeloutstart = ((ADAM7_IY[i] + (size_t)y * ADAM7_DY[i]) * (size_t)w
+ ADAM7_IX[i] + (size_t)x * ADAM7_DX[i]) * bytewidth;
for(b = 0; b < bytewidth; ++b) {
out[pixeloutstart + b] = in[pixelinstart + b];
}
}
}
}
else { /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
for(i = 0; i != 7; ++i) {
unsigned x, y, b;
unsigned ilinebits = bpp * passw[i];
unsigned olinebits = bpp * w;
size_t obp, ibp; /*bit pointers (for out and in buffer)*/
for(y = 0; y < passh[i]; ++y)
for(x = 0; x < passw[i]; ++x) {
ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
obp = (ADAM7_IY[i] + (size_t)y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + (size_t)x * ADAM7_DX[i]) * bpp;
for(b = 0; b < bpp; ++b) {
unsigned char bit = readBitFromReversedStream(&ibp, in);
setBitOfReversedStream(&obp, out, bit);
}
}
}
}
}
static void removePaddingBits(unsigned char * out, const unsigned char * in,
size_t olinebits, size_t ilinebits, unsigned h)
{
/*
After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
for the Adam7 code, the color convert code and the output to the user.
in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
only useful if (ilinebits - olinebits) is a value in the range 1..7
*/
unsigned y;
size_t diff = ilinebits - olinebits;
size_t ibp = 0, obp = 0; /*input and output bit pointers*/
for(y = 0; y < h; ++y) {
size_t x;
for(x = 0; x < olinebits; ++x) {
unsigned char bit = readBitFromReversedStream(&ibp, in);
setBitOfReversedStream(&obp, out, bit);
}
ibp += diff;
}
}
/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
the IDAT chunks (with filter index bytes and possible padding bits)
return value is error*/
static unsigned postProcessScanlines(unsigned char * out, unsigned char * in,
unsigned w, unsigned h, const LodePNGInfo * info_png)
{
/*
This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
Steps:
*) if no Adam7: 1) unfilter 2) remove padding bits (= possible extra bits per scanline if bpp < 8)
*) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
NOTE: the in buffer will be overwritten with intermediate data!
*/
unsigned bpp = lodepng_get_bpp(&info_png->color);
if(bpp == 0) return 31; /*error: invalid colortype*/
if(info_png->interlace_method == 0) {
if(bpp < 8 && w * bpp != ((w * bpp + 7u) / 8u) * 8u) {
CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp));
removePaddingBits(out, in, w * bpp, ((w * bpp + 7u) / 8u) * 8u, h);
}
/*we can immediately filter into the out buffer, no other steps needed*/
else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp));
}
else { /*interlace_method is 1 (Adam7)*/
unsigned passw[7], passh[7];
size_t filter_passstart[8], padded_passstart[8], passstart[8];
unsigned i;
Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
for(i = 0; i != 7; ++i) {
CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp));
/*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,
move bytes instead of bits or move not at all*/
if(bpp < 8) {
/*remove padding bits in scanlines; after this there still may be padding
bits between the different reduced images: each reduced image still starts nicely at a byte*/
removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp,
((passw[i] * bpp + 7u) / 8u) * 8u, passh[i]);
}
}
Adam7_deinterlace(out, in, w, h, bpp);
}
return 0;
}
static unsigned readChunk_PLTE(LodePNGColorMode * color, const unsigned char * data, size_t chunkLength)
{
unsigned pos = 0, i;
color->palettesize = chunkLength / 3u;
if(color->palettesize == 0 || color->palettesize > 256) return 38; /*error: palette too small or big*/
lodepng_color_mode_alloc_palette(color);
if(!color->palette && color->palettesize) {
color->palettesize = 0;
return 83; /*alloc fail*/
}
for(i = 0; i != color->palettesize; ++i) {
color->palette[4 * i + 0] = data[pos++]; /*R*/
color->palette[4 * i + 1] = data[pos++]; /*G*/
color->palette[4 * i + 2] = data[pos++]; /*B*/
color->palette[4 * i + 3] = 255; /*alpha*/
}
return 0; /* OK */
}
static unsigned readChunk_tRNS(LodePNGColorMode * color, const unsigned char * data, size_t chunkLength)
{
unsigned i;
if(color->colortype == LCT_PALETTE) {
/*error: more alpha values given than there are palette entries*/
if(chunkLength > color->palettesize) return 39;
for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i];
}
else if(color->colortype == LCT_GREY) {
/*error: this chunk must be 2 bytes for grayscale image*/
if(chunkLength != 2) return 30;
color->key_defined = 1;
color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1];
}
else if(color->colortype == LCT_RGB) {
/*error: this chunk must be 6 bytes for RGB image*/
if(chunkLength != 6) return 41;
color->key_defined = 1;
color->key_r = 256u * data[0] + data[1];
color->key_g = 256u * data[2] + data[3];
color->key_b = 256u * data[4] + data[5];
}
else return 42; /*error: tRNS chunk not allowed for other color models*/
return 0; /* OK */
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*background color chunk (bKGD)*/
static unsigned readChunk_bKGD(LodePNGInfo * info, const unsigned char * data, size_t chunkLength)
{
if(info->color.colortype == LCT_PALETTE) {
/*error: this chunk must be 1 byte for indexed color image*/
if(chunkLength != 1) return 43;
/*error: invalid palette index, or maybe this chunk appeared before PLTE*/
if(data[0] >= info->color.palettesize) return 103;
info->background_defined = 1;
info->background_r = info->background_g = info->background_b = data[0];
}
else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) {
/*error: this chunk must be 2 bytes for grayscale image*/
if(chunkLength != 2) return 44;
/*the values are truncated to bitdepth in the PNG file*/
info->background_defined = 1;
info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1];
}
else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) {
/*error: this chunk must be 6 bytes for grayscale image*/
if(chunkLength != 6) return 45;
/*the values are truncated to bitdepth in the PNG file*/
info->background_defined = 1;
info->background_r = 256u * data[0] + data[1];
info->background_g = 256u * data[2] + data[3];
info->background_b = 256u * data[4] + data[5];
}
return 0; /* OK */
}
/*text chunk (tEXt)*/
static unsigned readChunk_tEXt(LodePNGInfo * info, const unsigned char * data, size_t chunkLength)
{
unsigned error = 0;
char * key = 0, * str = 0;
while(!error) { /*not really a while loop, only used to break on error*/
unsigned length, string2_begin;
length = 0;
while(length < chunkLength && data[length] != 0) ++length;
/*even though it's not allowed by the standard, no error is thrown if
there's no null termination char, if the text is empty*/
if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
key = (char *)lodepng_malloc(length + 1);
if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
lodepng_memcpy(key, data, length);
key[length] = 0;
string2_begin = length + 1; /*skip keyword null terminator*/
length = (unsigned)(chunkLength < string2_begin ? 0 : chunkLength - string2_begin);
str = (char *)lodepng_malloc(length + 1);
if(!str) CERROR_BREAK(error, 83); /*alloc fail*/
lodepng_memcpy(str, data + string2_begin, length);
str[length] = 0;
error = lodepng_add_text(info, key, str);
break;
}
lodepng_free(key);
lodepng_free(str);
return error;
}
/*compressed text chunk (zTXt)*/
static unsigned readChunk_zTXt(LodePNGInfo * info, const LodePNGDecoderSettings * decoder,
const unsigned char * data, size_t chunkLength)
{
unsigned error = 0;
/*copy the object to change parameters in it*/
LodePNGDecompressSettings zlibsettings = decoder->zlibsettings;
unsigned length, string2_begin;
char * key = 0;
unsigned char * str = 0;
size_t size = 0;
while(!error) { /*not really a while loop, only used to break on error*/
for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
key = (char *)lodepng_malloc(length + 1);
if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
lodepng_memcpy(key, data, length);
key[length] = 0;
if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
string2_begin = length + 2;
if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
length = (unsigned)chunkLength - string2_begin;
zlibsettings.max_output_size = decoder->max_text_size;
/*will fail if zlib error, e.g. if length is too small*/
error = zlib_decompress(&str, &size, 0, &data[string2_begin],
length, &zlibsettings);
/*error: compressed text larger than decoder->max_text_size*/
if(error && size > zlibsettings.max_output_size) error = 112;
if(error) break;
error = lodepng_add_text_sized(info, key, (char *)str, size);
break;
}
lodepng_free(key);
lodepng_free(str);
return error;
}
/*international text chunk (iTXt)*/
static unsigned readChunk_iTXt(LodePNGInfo * info, const LodePNGDecoderSettings * decoder,
const unsigned char * data, size_t chunkLength)
{
unsigned error = 0;
unsigned i;
/*copy the object to change parameters in it*/
LodePNGDecompressSettings zlibsettings = decoder->zlibsettings;
unsigned length, begin, compressed;
char * key = 0, * langtag = 0, * transkey = 0;
while(!error) { /*not really a while loop, only used to break on error*/
/*Quick check if the chunk length isn't too small. Even without check
it'd still fail with other error checks below if it's too short. This just gives a different error code.*/
if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/
/*read the key*/
for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/
if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
key = (char *)lodepng_malloc(length + 1);
if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
lodepng_memcpy(key, data, length);
key[length] = 0;
/*read the compression method*/
compressed = data[length + 1];
if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
/*even though it's not allowed by the standard, no error is thrown if
there's no null termination char, if the text is empty for the next 3 texts*/
/*read the langtag*/
begin = length + 3;
length = 0;
for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
langtag = (char *)lodepng_malloc(length + 1);
if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/
lodepng_memcpy(langtag, data + begin, length);
langtag[length] = 0;
/*read the transkey*/
begin += length + 1;
length = 0;
for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
transkey = (char *)lodepng_malloc(length + 1);
if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/
lodepng_memcpy(transkey, data + begin, length);
transkey[length] = 0;
/*read the actual text*/
begin += length + 1;
length = (unsigned)chunkLength < begin ? 0 : (unsigned)chunkLength - begin;
if(compressed) {
unsigned char * str = 0;
size_t size = 0;
zlibsettings.max_output_size = decoder->max_text_size;
/*will fail if zlib error, e.g. if length is too small*/
error = zlib_decompress(&str, &size, 0, &data[begin],
length, &zlibsettings);
/*error: compressed text larger than decoder->max_text_size*/
if(error && size > zlibsettings.max_output_size) error = 112;
if(!error) error = lodepng_add_itext_sized(info, key, langtag, transkey, (char *)str, size);
lodepng_free(str);
}
else {
error = lodepng_add_itext_sized(info, key, langtag, transkey, (char *)(data + begin), length);
}
break;
}
lodepng_free(key);
lodepng_free(langtag);
lodepng_free(transkey);
return error;
}
static unsigned readChunk_tIME(LodePNGInfo * info, const unsigned char * data, size_t chunkLength)
{
if(chunkLength != 7) return 73; /*invalid tIME chunk size*/
info->time_defined = 1;
info->time.year = 256u * data[0] + data[1];
info->time.month = data[2];
info->time.day = data[3];
info->time.hour = data[4];
info->time.minute = data[5];
info->time.second = data[6];
return 0; /* OK */
}
static unsigned readChunk_pHYs(LodePNGInfo * info, const unsigned char * data, size_t chunkLength)
{
if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/
info->phys_defined = 1;
info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7];
info->phys_unit = data[8];
return 0; /* OK */
}
static unsigned readChunk_gAMA(LodePNGInfo * info, const unsigned char * data, size_t chunkLength)
{
if(chunkLength != 4) return 96; /*invalid gAMA chunk size*/
info->gama_defined = 1;
info->gama_gamma = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
return 0; /* OK */
}
static unsigned readChunk_cHRM(LodePNGInfo * info, const unsigned char * data, size_t chunkLength)
{
if(chunkLength != 32) return 97; /*invalid cHRM chunk size*/
info->chrm_defined = 1;
info->chrm_white_x = 16777216u * data[ 0] + 65536u * data[ 1] + 256u * data[ 2] + data[ 3];
info->chrm_white_y = 16777216u * data[ 4] + 65536u * data[ 5] + 256u * data[ 6] + data[ 7];
info->chrm_red_x = 16777216u * data[ 8] + 65536u * data[ 9] + 256u * data[10] + data[11];
info->chrm_red_y = 16777216u * data[12] + 65536u * data[13] + 256u * data[14] + data[15];
info->chrm_green_x = 16777216u * data[16] + 65536u * data[17] + 256u * data[18] + data[19];
info->chrm_green_y = 16777216u * data[20] + 65536u * data[21] + 256u * data[22] + data[23];
info->chrm_blue_x = 16777216u * data[24] + 65536u * data[25] + 256u * data[26] + data[27];
info->chrm_blue_y = 16777216u * data[28] + 65536u * data[29] + 256u * data[30] + data[31];
return 0; /* OK */
}
static unsigned readChunk_sRGB(LodePNGInfo * info, const unsigned char * data, size_t chunkLength)
{
if(chunkLength != 1) return 98; /*invalid sRGB chunk size (this one is never ignored)*/
info->srgb_defined = 1;
info->srgb_intent = data[0];
return 0; /* OK */
}
static unsigned readChunk_iCCP(LodePNGInfo * info, const LodePNGDecoderSettings * decoder,
const unsigned char * data, size_t chunkLength)
{
unsigned error = 0;
unsigned i;
size_t size = 0;
/*copy the object to change parameters in it*/
LodePNGDecompressSettings zlibsettings = decoder->zlibsettings;
unsigned length, string2_begin;
info->iccp_defined = 1;
if(info->iccp_name) lodepng_clear_icc(info);
for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
if(length + 2 >= chunkLength) return 75; /*no null termination, corrupt?*/
if(length < 1 || length > 79) return 89; /*keyword too short or long*/
info->iccp_name = (char *)lodepng_malloc(length + 1);
if(!info->iccp_name) return 83; /*alloc fail*/
info->iccp_name[length] = 0;
for(i = 0; i != length; ++i) info->iccp_name[i] = (char)data[i];
if(data[length + 1] != 0) return 72; /*the 0 byte indicating compression must be 0*/
string2_begin = length + 2;
if(string2_begin > chunkLength) return 75; /*no null termination, corrupt?*/
length = (unsigned)chunkLength - string2_begin;
zlibsettings.max_output_size = decoder->max_icc_size;
error = zlib_decompress(&info->iccp_profile, &size, 0,
&data[string2_begin],
length, &zlibsettings);
/*error: ICC profile larger than decoder->max_icc_size*/
if(error && size > zlibsettings.max_output_size) error = 113;
info->iccp_profile_size = size;
if(!error && !info->iccp_profile_size) error = 100; /*invalid ICC profile size*/
return error;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
unsigned lodepng_inspect_chunk(LodePNGState * state, size_t pos,
const unsigned char * in, size_t insize)
{
const unsigned char * chunk = in + pos;
unsigned chunkLength;
const unsigned char * data;
unsigned unhandled = 0;
unsigned error = 0;
if(pos + 4 > insize) return 30;
chunkLength = lodepng_chunk_length(chunk);
if(chunkLength > 2147483647) return 63;
data = lodepng_chunk_data_const(chunk);
if(data + chunkLength + 4 > in + insize) return 30;
if(lodepng_chunk_type_equals(chunk, "PLTE")) {
error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
}
else if(lodepng_chunk_type_equals(chunk, "tRNS")) {
error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
}
else if(lodepng_chunk_type_equals(chunk, "bKGD")) {
error = readChunk_bKGD(&state->info_png, data, chunkLength);
}
else if(lodepng_chunk_type_equals(chunk, "tEXt")) {
error = readChunk_tEXt(&state->info_png, data, chunkLength);
}
else if(lodepng_chunk_type_equals(chunk, "zTXt")) {
error = readChunk_zTXt(&state->info_png, &state->decoder, data, chunkLength);
}
else if(lodepng_chunk_type_equals(chunk, "iTXt")) {
error = readChunk_iTXt(&state->info_png, &state->decoder, data, chunkLength);
}
else if(lodepng_chunk_type_equals(chunk, "tIME")) {
error = readChunk_tIME(&state->info_png, data, chunkLength);
}
else if(lodepng_chunk_type_equals(chunk, "pHYs")) {
error = readChunk_pHYs(&state->info_png, data, chunkLength);
}
else if(lodepng_chunk_type_equals(chunk, "gAMA")) {
error = readChunk_gAMA(&state->info_png, data, chunkLength);
}
else if(lodepng_chunk_type_equals(chunk, "cHRM")) {
error = readChunk_cHRM(&state->info_png, data, chunkLength);
}
else if(lodepng_chunk_type_equals(chunk, "sRGB")) {
error = readChunk_sRGB(&state->info_png, data, chunkLength);
}
else if(lodepng_chunk_type_equals(chunk, "iCCP")) {
error = readChunk_iCCP(&state->info_png, &state->decoder, data, chunkLength);
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
else {
/* unhandled chunk is ok (is not an error) */
unhandled = 1;
}
if(!error && !unhandled && !state->decoder.ignore_crc) {
if(lodepng_chunk_check_crc(chunk)) return 57; /*invalid CRC*/
}
return error;
}
/*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
static void decodeGeneric(unsigned char ** out, unsigned * w, unsigned * h,
LodePNGState * state,
const unsigned char * in, size_t insize)
{
unsigned char IEND = 0;
const unsigned char * chunk;
unsigned char * idat; /*the data from idat chunks, zlib compressed*/
size_t idatsize = 0;
unsigned char * scanlines = 0;
size_t scanlines_size = 0, expected_size = 0;
size_t outsize = 0;
/*for unknown chunk order*/
unsigned unknown = 0;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/* safe output values in case error happens */
*out = 0;
*w = *h = 0;
state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/
if(state->error) return;
if(lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) {
CERROR_RETURN(state->error, 92); /*overflow possible due to amount of pixels*/
}
/*the input filesize is a safe upper bound for the sum of idat chunks size*/
idat = (unsigned char *)lodepng_malloc(insize);
if(!idat) CERROR_RETURN(state->error, 83); /*alloc fail*/
chunk = &in[33]; /*first byte of the first chunk after the header*/
/*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
IDAT data is put at the start of the in buffer*/
while(!IEND && !state->error) {
unsigned chunkLength;
const unsigned char * data; /*the data in the chunk*/
/*error: size of the in buffer too small to contain next chunk*/
if((size_t)((chunk - in) + 12) > insize || chunk < in) {
if(state->decoder.ignore_end) break; /*other errors may still happen though*/
CERROR_BREAK(state->error, 30);
}
/*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/
chunkLength = lodepng_chunk_length(chunk);
/*error: chunk length larger than the max PNG chunk size*/
if(chunkLength > 2147483647) {
if(state->decoder.ignore_end) break; /*other errors may still happen though*/
CERROR_BREAK(state->error, 63);
}
if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) {
CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/
}
data = lodepng_chunk_data_const(chunk);
unknown = 0;
/*IDAT chunk, containing compressed image data*/
if(lodepng_chunk_type_equals(chunk, "IDAT")) {
size_t newsize;
if(lodepng_addofl(idatsize, chunkLength, &newsize)) CERROR_BREAK(state->error, 95);
if(newsize > insize) CERROR_BREAK(state->error, 95);
lodepng_memcpy(idat + idatsize, data, chunkLength);
idatsize += chunkLength;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
critical_pos = 3;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
else if(lodepng_chunk_type_equals(chunk, "IEND")) {
/*IEND chunk*/
IEND = 1;
}
else if(lodepng_chunk_type_equals(chunk, "PLTE")) {
/*palette chunk (PLTE)*/
state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
if(state->error) break;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
critical_pos = 2;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
else if(lodepng_chunk_type_equals(chunk, "tRNS")) {
/*palette transparency chunk (tRNS). Even though this one is an ancillary chunk , it is still compiled
in without 'LODEPNG_COMPILE_ANCILLARY_CHUNKS' because it contains essential color information that
affects the alpha channel of pixels. */
state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
if(state->error) break;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*background color chunk (bKGD)*/
}
else if(lodepng_chunk_type_equals(chunk, "bKGD")) {
state->error = readChunk_bKGD(&state->info_png, data, chunkLength);
if(state->error) break;
}
else if(lodepng_chunk_type_equals(chunk, "tEXt")) {
/*text chunk (tEXt)*/
if(state->decoder.read_text_chunks) {
state->error = readChunk_tEXt(&state->info_png, data, chunkLength);
if(state->error) break;
}
}
else if(lodepng_chunk_type_equals(chunk, "zTXt")) {
/*compressed text chunk (zTXt)*/
if(state->decoder.read_text_chunks) {
state->error = readChunk_zTXt(&state->info_png, &state->decoder, data, chunkLength);
if(state->error) break;
}
}
else if(lodepng_chunk_type_equals(chunk, "iTXt")) {
/*international text chunk (iTXt)*/
if(state->decoder.read_text_chunks) {
state->error = readChunk_iTXt(&state->info_png, &state->decoder, data, chunkLength);
if(state->error) break;
}
}
else if(lodepng_chunk_type_equals(chunk, "tIME")) {
state->error = readChunk_tIME(&state->info_png, data, chunkLength);
if(state->error) break;
}
else if(lodepng_chunk_type_equals(chunk, "pHYs")) {
state->error = readChunk_pHYs(&state->info_png, data, chunkLength);
if(state->error) break;
}
else if(lodepng_chunk_type_equals(chunk, "gAMA")) {
state->error = readChunk_gAMA(&state->info_png, data, chunkLength);
if(state->error) break;
}
else if(lodepng_chunk_type_equals(chunk, "cHRM")) {
state->error = readChunk_cHRM(&state->info_png, data, chunkLength);
if(state->error) break;
}
else if(lodepng_chunk_type_equals(chunk, "sRGB")) {
state->error = readChunk_sRGB(&state->info_png, data, chunkLength);
if(state->error) break;
}
else if(lodepng_chunk_type_equals(chunk, "iCCP")) {
state->error = readChunk_iCCP(&state->info_png, &state->decoder, data, chunkLength);
if(state->error) break;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
else { /*it's not an implemented chunk type, so ignore it: skip over the data*/
/*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
if(!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) {
CERROR_BREAK(state->error, 69);
}
unknown = 1;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
if(state->decoder.remember_unknown_chunks) {
state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1],
&state->info_png.unknown_chunks_size[critical_pos - 1], chunk);
if(state->error) break;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
if(!state->decoder.ignore_crc && !unknown) { /*check CRC if wanted, only on known chunk types*/
if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/
}
if(!IEND) chunk = lodepng_chunk_next_const(chunk, in + insize);
}
if(!state->error && state->info_png.color.colortype == LCT_PALETTE && !state->info_png.color.palette) {
state->error = 106; /* error: PNG file must have PLTE chunk if color type is palette */
}
if(!state->error) {
/*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation.
If the decompressed size does not match the prediction, the image must be corrupt.*/
if(state->info_png.interlace_method == 0) {
size_t bpp = lodepng_get_bpp(&state->info_png.color);
expected_size = lodepng_get_raw_size_idat(*w, *h, bpp);
}
else {
size_t bpp = lodepng_get_bpp(&state->info_png.color);
/*Adam-7 interlaced: expected size is the sum of the 7 sub-images sizes*/
expected_size = 0;
expected_size += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, bpp);
if(*w > 4) expected_size += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, bpp);
expected_size += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, bpp);
if(*w > 2) expected_size += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, bpp);
expected_size += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, bpp);
if(*w > 1) expected_size += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, bpp);
expected_size += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, bpp);
}
state->error = zlib_decompress(&scanlines, &scanlines_size, expected_size, idat, idatsize,
&state->decoder.zlibsettings);
}
if(!state->error && scanlines_size != expected_size) state->error = 91; /*decompressed size doesn't match prediction*/
lodepng_free(idat);
if(!state->error) {
outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color);
*out = (unsigned char *)lv_draw_buf_malloc(outsize, LV_COLOR_FORMAT_ARGB8888);
if(!*out) state->error = 83; /*alloc fail*/
}
if(!state->error) {
lodepng_memset(*out, 0, outsize);
state->error = postProcessScanlines(*out, scanlines, *w, *h, &state->info_png);
}
lodepng_free(scanlines);
}
unsigned lodepng_decode(unsigned char ** out, unsigned * w, unsigned * h,
LodePNGState * state,
const unsigned char * in, size_t insize)
{
*out = 0;
decodeGeneric(out, w, h, state, in, insize);
if(state->error) return state->error;
if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) {
/*same color type, no copying or converting of data needed*/
/*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
the raw image has to the end user*/
if(!state->decoder.color_convert) {
state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);
if(state->error) return state->error;
}
}
else { /*color conversion needed*/
unsigned char * data = *out;
size_t outsize;
/*TODO: check if this works according to the statement in the documentation: "The converter can convert
from grayscale input color type, to 8-bit grayscale or grayscale with alpha"*/
if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA)
&& !(state->info_raw.bitdepth == 8)) {
return 56; /*unsupported color mode conversion*/
}
outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);
*out = (unsigned char *)lodepng_malloc(outsize);
if(!(*out)) {
state->error = 83; /*alloc fail*/
}
else state->error = lodepng_convert(*out, data, &state->info_raw,
&state->info_png.color, *w, *h);
lodepng_free(data);
}
return state->error;
}
unsigned lodepng_decode_memory(unsigned char ** out, unsigned * w, unsigned * h, const unsigned char * in,
size_t insize, LodePNGColorType colortype, unsigned bitdepth)
{
unsigned error;
LodePNGState state;
lodepng_state_init(&state);
state.info_raw.colortype = colortype;
state.info_raw.bitdepth = bitdepth;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*disable reading things that this function doesn't output*/
state.decoder.read_text_chunks = 0;
state.decoder.remember_unknown_chunks = 0;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
error = lodepng_decode(out, w, h, &state, in, insize);
lodepng_state_cleanup(&state);
return error;
}
unsigned lodepng_decode32(unsigned char ** out, unsigned * w, unsigned * h, const unsigned char * in, size_t insize)
{
return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8);
}
unsigned lodepng_decode24(unsigned char ** out, unsigned * w, unsigned * h, const unsigned char * in, size_t insize)
{
return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8);
}
#ifdef LODEPNG_COMPILE_DISK
unsigned lodepng_decode_file(unsigned char ** out, unsigned * w, unsigned * h, const char * filename,
LodePNGColorType colortype, unsigned bitdepth)
{
unsigned char * buffer = 0;
size_t buffersize;
unsigned error;
/* safe output values in case error happens */
*out = 0;
*w = *h = 0;
error = lodepng_load_file(&buffer, &buffersize, filename);
if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth);
lodepng_free(buffer);
return error;
}
unsigned lodepng_decode32_file(unsigned char ** out, unsigned * w, unsigned * h, const char * filename)
{
return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8);
}
unsigned lodepng_decode24_file(unsigned char ** out, unsigned * w, unsigned * h, const char * filename)
{
return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8);
}
#endif /*LODEPNG_COMPILE_DISK*/
void lodepng_decoder_settings_init(LodePNGDecoderSettings * settings)
{
settings->color_convert = 1;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
settings->read_text_chunks = 1;
settings->remember_unknown_chunks = 0;
settings->max_text_size = 16777216;
settings->max_icc_size = 16777216; /* 16MB is much more than enough for any reasonable ICC profile */
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
settings->ignore_crc = 0;
settings->ignore_critical = 0;
settings->ignore_end = 0;
lodepng_decompress_settings_init(&settings->zlibsettings);
}
#endif /*LODEPNG_COMPILE_DECODER*/
#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
void lodepng_state_init(LodePNGState * state)
{
#ifdef LODEPNG_COMPILE_DECODER
lodepng_decoder_settings_init(&state->decoder);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
lodepng_encoder_settings_init(&state->encoder);
#endif /*LODEPNG_COMPILE_ENCODER*/
lodepng_color_mode_init(&state->info_raw);
lodepng_info_init(&state->info_png);
state->error = 1;
}
void lodepng_state_cleanup(LodePNGState * state)
{
lodepng_color_mode_cleanup(&state->info_raw);
lodepng_info_cleanup(&state->info_png);
}
void lodepng_state_copy(LodePNGState * dest, const LodePNGState * source)
{
lodepng_state_cleanup(dest);
*dest = *source;
lodepng_color_mode_init(&dest->info_raw);
lodepng_info_init(&dest->info_png);
dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw);
if(dest->error) return;
dest->error = lodepng_info_copy(&dest->info_png, &source->info_png);
if(dest->error) return;
}
#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
#ifdef LODEPNG_COMPILE_ENCODER
/* ////////////////////////////////////////////////////////////////////////// */
/* / PNG Encoder / */
/* ////////////////////////////////////////////////////////////////////////// */
static unsigned writeSignature(ucvector * out)
{
size_t pos = out->size;
const unsigned char signature[] = {137, 80, 78, 71, 13, 10, 26, 10};
/*8 bytes PNG signature, aka the magic bytes*/
if(!ucvector_resize(out, out->size + 8)) return 83; /*alloc fail*/
lodepng_memcpy(out->data + pos, signature, 8);
return 0;
}
static unsigned addChunk_IHDR(ucvector * out, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method)
{
unsigned char * chunk, * data;
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 13, "IHDR"));
data = chunk + 8;
lodepng_set32bitInt(data + 0, w); /*width*/
lodepng_set32bitInt(data + 4, h); /*height*/
data[8] = (unsigned char)bitdepth; /*bit depth*/
data[9] = (unsigned char)colortype; /*color type*/
data[10] = 0; /*compression method*/
data[11] = 0; /*filter method*/
data[12] = interlace_method; /*interlace method*/
lodepng_chunk_generate_crc(chunk);
return 0;
}
/* only adds the chunk if needed (there is a key or palette with alpha) */
static unsigned addChunk_PLTE(ucvector * out, const LodePNGColorMode * info)
{
unsigned char * chunk;
size_t i, j = 8;
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, info->palettesize * 3, "PLTE"));
for(i = 0; i != info->palettesize; ++i) {
/*add all channels except alpha channel*/
chunk[j++] = info->palette[i * 4 + 0];
chunk[j++] = info->palette[i * 4 + 1];
chunk[j++] = info->palette[i * 4 + 2];
}
lodepng_chunk_generate_crc(chunk);
return 0;
}
static unsigned addChunk_tRNS(ucvector * out, const LodePNGColorMode * info)
{
unsigned char * chunk = 0;
if(info->colortype == LCT_PALETTE) {
size_t i, amount = info->palettesize;
/*the tail of palette values that all have 255 as alpha, does not have to be encoded*/
for(i = info->palettesize; i != 0; --i) {
if(info->palette[4 * (i - 1) + 3] != 255) break;
--amount;
}
if(amount) {
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, amount, "tRNS"));
/*add the alpha channel values from the palette*/
for(i = 0; i != amount; ++i) chunk[8 + i] = info->palette[4 * i + 3];
}
}
else if(info->colortype == LCT_GREY) {
if(info->key_defined) {
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "tRNS"));
chunk[8] = (unsigned char)(info->key_r >> 8);
chunk[9] = (unsigned char)(info->key_r & 255);
}
}
else if(info->colortype == LCT_RGB) {
if(info->key_defined) {
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 6, "tRNS"));
chunk[8] = (unsigned char)(info->key_r >> 8);
chunk[9] = (unsigned char)(info->key_r & 255);
chunk[10] = (unsigned char)(info->key_g >> 8);
chunk[11] = (unsigned char)(info->key_g & 255);
chunk[12] = (unsigned char)(info->key_b >> 8);
chunk[13] = (unsigned char)(info->key_b & 255);
}
}
if(chunk) lodepng_chunk_generate_crc(chunk);
return 0;
}
static unsigned addChunk_IDAT(ucvector * out, const unsigned char * data, size_t datasize,
LodePNGCompressSettings * zlibsettings)
{
unsigned error = 0;
unsigned char * zlib = 0;
size_t zlibsize = 0;
error = zlib_compress(&zlib, &zlibsize, data, datasize, zlibsettings);
if(!error) {
error = lodepng_chunk_createv(out, zlibsize, "IDAT", zlib);
}
lodepng_free(zlib);
return error;
}
static unsigned addChunk_IEND(ucvector * out)
{
return lodepng_chunk_createv(out, 0, "IEND", 0);
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
static unsigned addChunk_tEXt(ucvector * out, const char * keyword, const char * textstring)
{
unsigned char * chunk = 0;
size_t keysize = lodepng_strlen(keyword), textsize = lodepng_strlen(textstring);
size_t size = keysize + 1 + textsize;
if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, size, "tEXt"));
lodepng_memcpy(chunk + 8, keyword, keysize);
chunk[8 + keysize] = 0; /*null termination char*/
lodepng_memcpy(chunk + 9 + keysize, textstring, textsize);
lodepng_chunk_generate_crc(chunk);
return 0;
}
static unsigned addChunk_zTXt(ucvector * out, const char * keyword, const char * textstring,
LodePNGCompressSettings * zlibsettings)
{
unsigned error = 0;
unsigned char * chunk = 0;
unsigned char * compressed = 0;
size_t compressedsize = 0;
size_t textsize = lodepng_strlen(textstring);
size_t keysize = lodepng_strlen(keyword);
if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/
error = zlib_compress(&compressed, &compressedsize,
(const unsigned char *)textstring, textsize, zlibsettings);
if(!error) {
size_t size = keysize + 2 + compressedsize;
error = lodepng_chunk_init(&chunk, out, size, "zTXt");
}
if(!error) {
lodepng_memcpy(chunk + 8, keyword, keysize);
chunk[8 + keysize] = 0; /*null termination char*/
chunk[9 + keysize] = 0; /*compression method: 0*/
lodepng_memcpy(chunk + 10 + keysize, compressed, compressedsize);
lodepng_chunk_generate_crc(chunk);
}
lodepng_free(compressed);
return error;
}
static unsigned addChunk_iTXt(ucvector * out, unsigned compress, const char * keyword, const char * langtag,
const char * transkey, const char * textstring, LodePNGCompressSettings * zlibsettings)
{
unsigned error = 0;
unsigned char * chunk = 0;
unsigned char * compressed = 0;
size_t compressedsize = 0;
size_t textsize = lodepng_strlen(textstring);
size_t keysize = lodepng_strlen(keyword), langsize = lodepng_strlen(langtag), transsize = lodepng_strlen(transkey);
if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/
if(compress) {
error = zlib_compress(&compressed, &compressedsize,
(const unsigned char *)textstring, textsize, zlibsettings);
}
if(!error) {
size_t size = keysize + 3 + langsize + 1 + transsize + 1 + (compress ? compressedsize : textsize);
error = lodepng_chunk_init(&chunk, out, size, "iTXt");
}
if(!error) {
size_t pos = 8;
lodepng_memcpy(chunk + pos, keyword, keysize);
pos += keysize;
chunk[pos++] = 0; /*null termination char*/
chunk[pos++] = (compress ? 1 : 0); /*compression flag*/
chunk[pos++] = 0; /*compression method: 0*/
lodepng_memcpy(chunk + pos, langtag, langsize);
pos += langsize;
chunk[pos++] = 0; /*null termination char*/
lodepng_memcpy(chunk + pos, transkey, transsize);
pos += transsize;
chunk[pos++] = 0; /*null termination char*/
if(compress) {
lodepng_memcpy(chunk + pos, compressed, compressedsize);
}
else {
lodepng_memcpy(chunk + pos, textstring, textsize);
}
lodepng_chunk_generate_crc(chunk);
}
lodepng_free(compressed);
return error;
}
static unsigned addChunk_bKGD(ucvector * out, const LodePNGInfo * info)
{
unsigned char * chunk = 0;
if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) {
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "bKGD"));
chunk[8] = (unsigned char)(info->background_r >> 8);
chunk[9] = (unsigned char)(info->background_r & 255);
}
else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) {
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 6, "bKGD"));
chunk[8] = (unsigned char)(info->background_r >> 8);
chunk[9] = (unsigned char)(info->background_r & 255);
chunk[10] = (unsigned char)(info->background_g >> 8);
chunk[11] = (unsigned char)(info->background_g & 255);
chunk[12] = (unsigned char)(info->background_b >> 8);
chunk[13] = (unsigned char)(info->background_b & 255);
}
else if(info->color.colortype == LCT_PALETTE) {
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 1, "bKGD"));
chunk[8] = (unsigned char)(info->background_r & 255); /*palette index*/
}
if(chunk) lodepng_chunk_generate_crc(chunk);
return 0;
}
static unsigned addChunk_tIME(ucvector * out, const LodePNGTime * time)
{
unsigned char * chunk;
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 7, "tIME"));
chunk[8] = (unsigned char)(time->year >> 8);
chunk[9] = (unsigned char)(time->year & 255);
chunk[10] = (unsigned char)time->month;
chunk[11] = (unsigned char)time->day;
chunk[12] = (unsigned char)time->hour;
chunk[13] = (unsigned char)time->minute;
chunk[14] = (unsigned char)time->second;
lodepng_chunk_generate_crc(chunk);
return 0;
}
static unsigned addChunk_pHYs(ucvector * out, const LodePNGInfo * info)
{
unsigned char * chunk;
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 9, "pHYs"));
lodepng_set32bitInt(chunk + 8, info->phys_x);
lodepng_set32bitInt(chunk + 12, info->phys_y);
chunk[16] = info->phys_unit;
lodepng_chunk_generate_crc(chunk);
return 0;
}
static unsigned addChunk_gAMA(ucvector * out, const LodePNGInfo * info)
{
unsigned char * chunk;
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 4, "gAMA"));
lodepng_set32bitInt(chunk + 8, info->gama_gamma);
lodepng_chunk_generate_crc(chunk);
return 0;
}
static unsigned addChunk_cHRM(ucvector * out, const LodePNGInfo * info)
{
unsigned char * chunk;
CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 32, "cHRM"));
lodepng_set32bitInt(chunk + 8, info->chrm_white_x);
lodepng_set32bitInt(chunk + 12, info->chrm_white_y);
lodepng_set32bitInt(chunk + 16, info->chrm_red_x);
lodepng_set32bitInt(chunk + 20, info->chrm_red_y);
lodepng_set32bitInt(chunk + 24, info->chrm_green_x);
lodepng_set32bitInt(chunk + 28, info->chrm_green_y);
lodepng_set32bitInt(chunk + 32, info->chrm_blue_x);
lodepng_set32bitInt(chunk + 36, info->chrm_blue_y);
lodepng_chunk_generate_crc(chunk);
return 0;
}
static unsigned addChunk_sRGB(ucvector * out, const LodePNGInfo * info)
{
unsigned char data = info->srgb_intent;
return lodepng_chunk_createv(out, 1, "sRGB", &data);
}
static unsigned addChunk_iCCP(ucvector * out, const LodePNGInfo * info, LodePNGCompressSettings * zlibsettings)
{
unsigned error = 0;
unsigned char * chunk = 0;
unsigned char * compressed = 0;
size_t compressedsize = 0;
size_t keysize = lodepng_strlen(info->iccp_name);
if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/
error = zlib_compress(&compressed, &compressedsize,
info->iccp_profile, info->iccp_profile_size, zlibsettings);
if(!error) {
size_t size = keysize + 2 + compressedsize;
error = lodepng_chunk_init(&chunk, out, size, "iCCP");
}
if(!error) {
lodepng_memcpy(chunk + 8, info->iccp_name, keysize);
chunk[8 + keysize] = 0; /*null termination char*/
chunk[9 + keysize] = 0; /*compression method: 0*/
lodepng_memcpy(chunk + 10 + keysize, compressed, compressedsize);
lodepng_chunk_generate_crc(chunk);
}
lodepng_free(compressed);
return error;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
static void filterScanline(unsigned char * out, const unsigned char * scanline, const unsigned char * prevline,
size_t length, size_t bytewidth, unsigned char filterType)
{
size_t i;
switch(filterType) {
case 0: /*None*/
for(i = 0; i != length; ++i) out[i] = scanline[i];
break;
case 1: /*Sub*/
for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth];
break;
case 2: /*Up*/
if(prevline) {
for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i];
}
else {
for(i = 0; i != length; ++i) out[i] = scanline[i];
}
break;
case 3: /*Average*/
if(prevline) {
for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1);
for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1);
}
else {
for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1);
}
break;
case 4: /*Paeth*/
if(prevline) {
/*paethPredictor(0, prevline[i], 0) is always prevline[i]*/
for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]);
for(i = bytewidth; i < length; ++i) {
out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth]));
}
}
else {
for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
/*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/
for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]);
}
break;
default:
return; /*invalid filter type given*/
}
}
/* integer binary logarithm, max return value is 31 */
static size_t ilog2(size_t i)
{
size_t result = 0;
if(i >= 65536) {
result += 16;
i >>= 16;
}
if(i >= 256) {
result += 8;
i >>= 8;
}
if(i >= 16) {
result += 4;
i >>= 4;
}
if(i >= 4) {
result += 2;
i >>= 2;
}
if(i >= 2) {
result += 1; /*i >>= 1;*/
}
return result;
}
/* integer approximation for i * log2(i), helper function for LFS_ENTROPY */
static size_t ilog2i(size_t i)
{
size_t l;
if(i == 0) return 0;
l = ilog2(i);
/* approximate i*log2(i): l is integer logarithm, ((i - (1u << l)) << 1u)
linearly approximates the missing fractional part multiplied by i */
return i * l + ((i - (1u << l)) << 1u);
}
static unsigned filter(unsigned char * out, const unsigned char * in, unsigned w, unsigned h,
const LodePNGColorMode * color, const LodePNGEncoderSettings * settings)
{
/*
For PNG filter method 0
out must be a buffer with as size: h + (w * h * bpp + 7u) / 8u, because there are
the scanlines with 1 extra byte per scanline
*/
unsigned bpp = lodepng_get_bpp(color);
/*the width of a scanline in bytes, not including the filter type*/
size_t linebytes = lodepng_get_raw_size_idat(w, 1, bpp) - 1u;
/*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
size_t bytewidth = (bpp + 7u) / 8u;
const unsigned char * prevline = 0;
unsigned x, y;
unsigned error = 0;
LodePNGFilterStrategy strategy = settings->filter_strategy;
/*
There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard:
* If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e.
use fixed filtering, with the filter None).
* (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is
not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply
all five filters and select the filter that produces the smallest sum of absolute values per row.
This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true.
If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed,
but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum
heuristic is used.
*/
if(settings->filter_palette_zero &&
(color->colortype == LCT_PALETTE || color->bitdepth < 8)) strategy = LFS_ZERO;
if(bpp == 0) return 31; /*error: invalid color type*/
if(strategy >= LFS_ZERO && strategy <= LFS_FOUR) {
unsigned char type = (unsigned char)strategy;
for(y = 0; y != h; ++y) {
size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
size_t inindex = linebytes * y;
out[outindex] = type; /*filter type byte*/
filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
prevline = &in[inindex];
}
}
else if(strategy == LFS_MINSUM) {
/*adaptive filtering*/
unsigned char * attempt[5]; /*five filtering attempts, one for each filter type*/
size_t smallest = 0;
unsigned char type, bestType = 0;
for(type = 0; type != 5; ++type) {
attempt[type] = (unsigned char *)lodepng_malloc(linebytes);
if(!attempt[type]) error = 83; /*alloc fail*/
}
if(!error) {
for(y = 0; y != h; ++y) {
/*try the 5 filter types*/
for(type = 0; type != 5; ++type) {
size_t sum = 0;
filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
/*calculate the sum of the result*/
if(type == 0) {
for(x = 0; x != linebytes; ++x) sum += (unsigned char)(attempt[type][x]);
}
else {
for(x = 0; x != linebytes; ++x) {
/*For differences, each byte should be treated as signed, values above 127 are negative
(converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there.
This means filtertype 0 is almost never chosen, but that is justified.*/
unsigned char s = attempt[type][x];
sum += s < 128 ? s : (255U - s);
}
}
/*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
if(type == 0 || sum < smallest) {
bestType = type;
smallest = sum;
}
}
prevline = &in[y * linebytes];
/*now fill the out values*/
out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
}
}
for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
}
else if(strategy == LFS_ENTROPY) {
unsigned char * attempt[5]; /*five filtering attempts, one for each filter type*/
size_t bestSum = 0;
unsigned type, bestType = 0;
unsigned count[256];
for(type = 0; type != 5; ++type) {
attempt[type] = (unsigned char *)lodepng_malloc(linebytes);
if(!attempt[type]) error = 83; /*alloc fail*/
}
if(!error) {
for(y = 0; y != h; ++y) {
/*try the 5 filter types*/
for(type = 0; type != 5; ++type) {
size_t sum = 0;
filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
lodepng_memset(count, 0, 256 * sizeof(*count));
for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]];
++count[type]; /*the filter type itself is part of the scanline*/
for(x = 0; x != 256; ++x) {
sum += ilog2i(count[x]);
}
/*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
if(type == 0 || sum > bestSum) {
bestType = type;
bestSum = sum;
}
}
prevline = &in[y * linebytes];
/*now fill the out values*/
out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
}
}
for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
}
else if(strategy == LFS_PREDEFINED) {
for(y = 0; y != h; ++y) {
size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
size_t inindex = linebytes * y;
unsigned char type = settings->predefined_filters[y];
out[outindex] = type; /*filter type byte*/
filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
prevline = &in[inindex];
}
}
else if(strategy == LFS_BRUTE_FORCE) {
/*brute force filter chooser.
deflate the scanline after every filter attempt to see which one deflates best.
This is very slow and gives only slightly smaller, sometimes even larger, result*/
size_t size[5];
unsigned char * attempt[5]; /*five filtering attempts, one for each filter type*/
size_t smallest = 0;
unsigned type = 0, bestType = 0;
unsigned char * dummy;
LodePNGCompressSettings zlibsettings;
lodepng_memcpy(&zlibsettings, &settings->zlibsettings, sizeof(LodePNGCompressSettings));
/*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,
to simulate the true case where the tree is the same for the whole image. Sometimes it gives
better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare
cases better compression. It does make this a bit less slow, so it's worth doing this.*/
zlibsettings.btype = 1;
/*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG
images only, so disable it*/
zlibsettings.custom_zlib = 0;
zlibsettings.custom_deflate = 0;
for(type = 0; type != 5; ++type) {
attempt[type] = (unsigned char *)lodepng_malloc(linebytes);
if(!attempt[type]) error = 83; /*alloc fail*/
}
if(!error) {
for(y = 0; y != h; ++y) { /*try the 5 filter types*/
for(type = 0; type != 5; ++type) {
unsigned testsize = (unsigned)linebytes;
/*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/
filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
size[type] = 0;
dummy = 0;
zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings);
lodepng_free(dummy);
/*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/
if(type == 0 || size[type] < smallest) {
bestType = type;
smallest = size[type];
}
}
prevline = &in[y * linebytes];
out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
}
}
for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
}
else return 88; /* unknown filter strategy */
return error;
}
static void addPaddingBits(unsigned char * out, const unsigned char * in,
size_t olinebits, size_t ilinebits, unsigned h)
{
/*The opposite of the removePaddingBits function
olinebits must be >= ilinebits*/
unsigned y;
size_t diff = olinebits - ilinebits;
size_t obp = 0, ibp = 0; /*bit pointers*/
for(y = 0; y != h; ++y) {
size_t x;
for(x = 0; x < ilinebits; ++x) {
unsigned char bit = readBitFromReversedStream(&ibp, in);
setBitOfReversedStream(&obp, out, bit);
}
/*obp += diff; --> no, fill in some value in the padding bits too, to avoid
"Use of uninitialised value of size ###" warning from valgrind*/
for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0);
}
}
/*
in: non-interlaced image with size w*h
out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with
no padding bits between scanlines, but between reduced images so that each
reduced image starts at a byte.
bpp: bits per pixel
there are no padding bits, not between scanlines, not between reduced images
in has the following size in bits: w * h * bpp.
out is possibly bigger due to padding bits between reduced images
NOTE: comments about padding bits are only relevant if bpp < 8
*/
static void Adam7_interlace(unsigned char * out, const unsigned char * in, unsigned w, unsigned h, unsigned bpp)
{
unsigned passw[7], passh[7];
size_t filter_passstart[8], padded_passstart[8], passstart[8];
unsigned i;
Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
if(bpp >= 8) {
for(i = 0; i != 7; ++i) {
unsigned x, y, b;
size_t bytewidth = bpp / 8u;
for(y = 0; y < passh[i]; ++y)
for(x = 0; x < passw[i]; ++x) {
size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth;
for(b = 0; b < bytewidth; ++b) {
out[pixeloutstart + b] = in[pixelinstart + b];
}
}
}
}
else { /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
for(i = 0; i != 7; ++i) {
unsigned x, y, b;
unsigned ilinebits = bpp * passw[i];
unsigned olinebits = bpp * w;
size_t obp, ibp; /*bit pointers (for out and in buffer)*/
for(y = 0; y < passh[i]; ++y)
for(x = 0; x < passw[i]; ++x) {
ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
obp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
for(b = 0; b < bpp; ++b) {
unsigned char bit = readBitFromReversedStream(&ibp, in);
setBitOfReversedStream(&obp, out, bit);
}
}
}
}
}
/*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.
return value is error**/
static unsigned preProcessScanlines(unsigned char ** out, size_t * outsize, const unsigned char * in,
unsigned w, unsigned h,
const LodePNGInfo * info_png, const LodePNGEncoderSettings * settings)
{
/*
This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps:
*) if no Adam7: 1) add padding bits (= possible extra bits per scanline if bpp < 8) 2) filter
*) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter
*/
unsigned bpp = lodepng_get_bpp(&info_png->color);
unsigned error = 0;
if(info_png->interlace_method == 0) {
*outsize = h + (h * ((w * bpp + 7u) / 8u)); /*image size plus an extra byte per scanline + possible padding bits*/
*out = (unsigned char *)lodepng_malloc(*outsize);
if(!(*out) && (*outsize)) error = 83; /*alloc fail*/
if(!error) {
/*non multiple of 8 bits per scanline, padding bits needed per scanline*/
if(bpp < 8 && w * bpp != ((w * bpp + 7u) / 8u) * 8u) {
unsigned char * padded = (unsigned char *)lodepng_malloc(h * ((w * bpp + 7u) / 8u));
if(!padded) error = 83; /*alloc fail*/
if(!error) {
addPaddingBits(padded, in, ((w * bpp + 7u) / 8u) * 8u, w * bpp, h);
error = filter(*out, padded, w, h, &info_png->color, settings);
}
lodepng_free(padded);
}
else {
/*we can immediately filter into the out buffer, no other steps needed*/
error = filter(*out, in, w, h, &info_png->color, settings);
}
}
}
else { /*interlace_method is 1 (Adam7)*/
unsigned passw[7], passh[7];
size_t filter_passstart[8], padded_passstart[8], passstart[8];
unsigned char * adam7;
Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
*outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/
*out = (unsigned char *)lodepng_malloc(*outsize);
if(!(*out)) error = 83; /*alloc fail*/
adam7 = (unsigned char *)lodepng_malloc(passstart[7]);
if(!adam7 && passstart[7]) error = 83; /*alloc fail*/
if(!error && adam7) {
unsigned i;
Adam7_interlace(adam7, in, w, h, bpp);
for(i = 0; i != 7; ++i) {
if(bpp < 8) {
unsigned char * padded = (unsigned char *)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]);
if(!padded) ERROR_BREAK(83); /*alloc fail*/
addPaddingBits(padded, &adam7[passstart[i]],
((passw[i] * bpp + 7u) / 8u) * 8u, passw[i] * bpp, passh[i]);
error = filter(&(*out)[filter_passstart[i]], padded,
passw[i], passh[i], &info_png->color, settings);
lodepng_free(padded);
}
else {
error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]],
passw[i], passh[i], &info_png->color, settings);
}
if(error) break;
}
}
lodepng_free(adam7);
}
return error;
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
static unsigned addUnknownChunks(ucvector * out, unsigned char * data, size_t datasize)
{
unsigned char * inchunk = data;
while((size_t)(inchunk - data) < datasize) {
CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk));
out->allocsize = out->size; /*fix the allocsize again*/
inchunk = lodepng_chunk_next(inchunk, data + datasize);
}
return 0;
}
static unsigned isGrayICCProfile(const unsigned char * profile, unsigned size)
{
/*
It is a gray profile if bytes 16-19 are "GRAY", rgb profile if bytes 16-19
are "RGB ". We do not perform any full parsing of the ICC profile here, other
than check those 4 bytes to grayscale profile. Other than that, validity of
the profile is not checked. This is needed only because the PNG specification
requires using a non-gray color model if there is an ICC profile with "RGB "
(sadly limiting compression opportunities if the input data is grayscale RGB
data), and requires using a gray color model if it is "GRAY".
*/
if(size < 20) return 0;
return profile[16] == 'G' && profile[17] == 'R' && profile[18] == 'A' && profile[19] == 'Y';
}
static unsigned isRGBICCProfile(const unsigned char * profile, unsigned size)
{
/* See comment in isGrayICCProfile*/
if(size < 20) return 0;
return profile[16] == 'R' && profile[17] == 'G' && profile[18] == 'B' && profile[19] == ' ';
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
unsigned lodepng_encode(unsigned char ** out, size_t * outsize,
const unsigned char * image, unsigned w, unsigned h,
LodePNGState * state)
{
unsigned char * data = 0; /*uncompressed version of the IDAT chunk data*/
size_t datasize = 0;
ucvector outv = ucvector_init(NULL, 0);
LodePNGInfo info;
const LodePNGInfo * info_png = &state->info_png;
lodepng_info_init(&info);
/*provide some proper output values if error will happen*/
*out = 0;
*outsize = 0;
state->error = 0;
/*check input values validity*/
if((info_png->color.colortype == LCT_PALETTE || state->encoder.force_palette)
&& (info_png->color.palettesize == 0 || info_png->color.palettesize > 256)) {
state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/
goto cleanup;
}
if(state->encoder.zlibsettings.btype > 2) {
state->error = 61; /*error: invalid btype*/
goto cleanup;
}
if(info_png->interlace_method > 1) {
state->error = 71; /*error: invalid interlace mode*/
goto cleanup;
}
state->error = checkColorValidity(info_png->color.colortype, info_png->color.bitdepth);
if(state->error) goto cleanup; /*error: invalid color type given*/
state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth);
if(state->error) goto cleanup; /*error: invalid color type given*/
/* color convert and compute scanline filter types */
lodepng_info_copy(&info, &state->info_png);
if(state->encoder.auto_convert) {
LodePNGColorStats stats;
lodepng_color_stats_init(&stats);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
if(info_png->iccp_defined &&
isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) {
/*the PNG specification does not allow to use palette with a GRAY ICC profile, even
if the palette has only gray colors, so disallow it.*/
stats.allow_palette = 0;
}
if(info_png->iccp_defined &&
isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) {
/*the PNG specification does not allow to use grayscale color with RGB ICC profile, so disallow gray.*/
stats.allow_greyscale = 0;
}
#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */
state->error = lodepng_compute_color_stats(&stats, image, w, h, &state->info_raw);
if(state->error) goto cleanup;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
if(info_png->background_defined) {
/*the background chunk's color must be taken into account as well*/
unsigned r = 0, g = 0, b = 0;
LodePNGColorMode mode16 = lodepng_color_mode_make(LCT_RGB, 16);
lodepng_convert_rgb(&r, &g, &b, info_png->background_r, info_png->background_g, info_png->background_b, &mode16,
&info_png->color);
state->error = lodepng_color_stats_add(&stats, r, g, b, 65535);
if(state->error) goto cleanup;
}
#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */
state->error = auto_choose_color(&info.color, &state->info_raw, &stats);
if(state->error) goto cleanup;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*also convert the background chunk*/
if(info_png->background_defined) {
if(lodepng_convert_rgb(&info.background_r, &info.background_g, &info.background_b,
info_png->background_r, info_png->background_g, info_png->background_b, &info.color, &info_png->color)) {
state->error = 104;
goto cleanup;
}
}
#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
if(info_png->iccp_defined) {
unsigned gray_icc = isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size);
unsigned rgb_icc = isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size);
unsigned gray_png = info.color.colortype == LCT_GREY || info.color.colortype == LCT_GREY_ALPHA;
if(!gray_icc && !rgb_icc) {
state->error = 100; /* Disallowed profile color type for PNG */
goto cleanup;
}
if(gray_icc != gray_png) {
/*Not allowed to use RGB/RGBA/palette with GRAY ICC profile or vice versa,
or in case of auto_convert, it wasn't possible to find appropriate model*/
state->error = state->encoder.auto_convert ? 102 : 101;
goto cleanup;
}
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) {
unsigned char * converted;
size_t size = ((size_t)w * (size_t)h * (size_t)lodepng_get_bpp(&info.color) + 7u) / 8u;
converted = (unsigned char *)lodepng_malloc(size);
if(!converted && size) state->error = 83; /*alloc fail*/
if(!state->error) {
state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h);
}
if(!state->error) {
state->error = preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder);
}
lodepng_free(converted);
if(state->error) goto cleanup;
}
else {
state->error = preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder);
if(state->error) goto cleanup;
}
/* output all PNG chunks */ {
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
size_t i;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*write signature and chunks*/
state->error = writeSignature(&outv);
if(state->error) goto cleanup;
/*IHDR*/
state->error = addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method);
if(state->error) goto cleanup;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*unknown chunks between IHDR and PLTE*/
if(info.unknown_chunks_data[0]) {
state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]);
if(state->error) goto cleanup;
}
/*color profile chunks must come before PLTE */
if(info.iccp_defined) {
state->error = addChunk_iCCP(&outv, &info, &state->encoder.zlibsettings);
if(state->error) goto cleanup;
}
if(info.srgb_defined) {
state->error = addChunk_sRGB(&outv, &info);
if(state->error) goto cleanup;
}
if(info.gama_defined) {
state->error = addChunk_gAMA(&outv, &info);
if(state->error) goto cleanup;
}
if(info.chrm_defined) {
state->error = addChunk_cHRM(&outv, &info);
if(state->error) goto cleanup;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*PLTE*/
if(info.color.colortype == LCT_PALETTE) {
state->error = addChunk_PLTE(&outv, &info.color);
if(state->error) goto cleanup;
}
if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) {
/*force_palette means: write suggested palette for truecolor in PLTE chunk*/
state->error = addChunk_PLTE(&outv, &info.color);
if(state->error) goto cleanup;
}
/*tRNS (this will only add if when necessary) */
state->error = addChunk_tRNS(&outv, &info.color);
if(state->error) goto cleanup;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*bKGD (must come between PLTE and the IDAt chunks*/
if(info.background_defined) {
state->error = addChunk_bKGD(&outv, &info);
if(state->error) goto cleanup;
}
/*pHYs (must come before the IDAT chunks)*/
if(info.phys_defined) {
state->error = addChunk_pHYs(&outv, &info);
if(state->error) goto cleanup;
}
/*unknown chunks between PLTE and IDAT*/
if(info.unknown_chunks_data[1]) {
state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]);
if(state->error) goto cleanup;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*IDAT (multiple IDAT chunks must be consecutive)*/
state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings);
if(state->error) goto cleanup;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*tIME*/
if(info.time_defined) {
state->error = addChunk_tIME(&outv, &info.time);
if(state->error) goto cleanup;
}
/*tEXt and/or zTXt*/
for(i = 0; i != info.text_num; ++i) {
if(lodepng_strlen(info.text_keys[i]) > 79) {
state->error = 66; /*text chunk too large*/
goto cleanup;
}
if(lodepng_strlen(info.text_keys[i]) < 1) {
state->error = 67; /*text chunk too small*/
goto cleanup;
}
if(state->encoder.text_compression) {
state->error = addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings);
if(state->error) goto cleanup;
}
else {
state->error = addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]);
if(state->error) goto cleanup;
}
}
/*LodePNG version id in text chunk*/
if(state->encoder.add_id) {
unsigned already_added_id_text = 0;
for(i = 0; i != info.text_num; ++i) {
const char * k = info.text_keys[i];
/* Could use strcmp, but we're not calling or reimplementing this C library function for this use only */
if(k[0] == 'L' && k[1] == 'o' && k[2] == 'd' && k[3] == 'e' &&
k[4] == 'P' && k[5] == 'N' && k[6] == 'G' && k[7] == '\0') {
already_added_id_text = 1;
break;
}
}
if(already_added_id_text == 0) {
state->error = addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/
if(state->error) goto cleanup;
}
}
/*iTXt*/
for(i = 0; i != info.itext_num; ++i) {
if(lodepng_strlen(info.itext_keys[i]) > 79) {
state->error = 66; /*text chunk too large*/
goto cleanup;
}
if(lodepng_strlen(info.itext_keys[i]) < 1) {
state->error = 67; /*text chunk too small*/
goto cleanup;
}
state->error = addChunk_iTXt(
&outv, state->encoder.text_compression,
info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i],
&state->encoder.zlibsettings);
if(state->error) goto cleanup;
}
/*unknown chunks between IDAT and IEND*/
if(info.unknown_chunks_data[2]) {
state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]);
if(state->error) goto cleanup;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
state->error = addChunk_IEND(&outv);
if(state->error) goto cleanup;
}
cleanup:
lodepng_info_cleanup(&info);
lodepng_free(data);
/*instead of cleaning the vector up, give it to the output*/
*out = outv.data;
*outsize = outv.size;
return state->error;
}
unsigned lodepng_encode_memory(unsigned char ** out, size_t * outsize, const unsigned char * image,
unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
{
unsigned error;
LodePNGState state;
lodepng_state_init(&state);
state.info_raw.colortype = colortype;
state.info_raw.bitdepth = bitdepth;
state.info_png.color.colortype = colortype;
state.info_png.color.bitdepth = bitdepth;
lodepng_encode(out, outsize, image, w, h, &state);
error = state.error;
lodepng_state_cleanup(&state);
return error;
}
unsigned lodepng_encode32(unsigned char ** out, size_t * outsize, const unsigned char * image, unsigned w, unsigned h)
{
return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8);
}
unsigned lodepng_encode24(unsigned char ** out, size_t * outsize, const unsigned char * image, unsigned w, unsigned h)
{
return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8);
}
#ifdef LODEPNG_COMPILE_DISK
unsigned lodepng_encode_file(const char * filename, const unsigned char * image, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth)
{
unsigned char * buffer;
size_t buffersize;
unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth);
if(!error) error = lodepng_save_file(buffer, buffersize, filename);
lodepng_free(buffer);
return error;
}
unsigned lodepng_encode32_file(const char * filename, const unsigned char * image, unsigned w, unsigned h)
{
return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8);
}
unsigned lodepng_encode24_file(const char * filename, const unsigned char * image, unsigned w, unsigned h)
{
return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8);
}
#endif /*LODEPNG_COMPILE_DISK*/
void lodepng_encoder_settings_init(LodePNGEncoderSettings * settings)
{
lodepng_compress_settings_init(&settings->zlibsettings);
settings->filter_palette_zero = 1;
settings->filter_strategy = LFS_MINSUM;
settings->auto_convert = 1;
settings->force_palette = 0;
settings->predefined_filters = 0;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
settings->add_id = 0;
settings->text_compression = 1;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ERROR_TEXT
/*
This returns the description of a numerical error code in English. This is also
the documentation of all the error codes.
*/
const char * lodepng_error_text(unsigned code)
{
switch(code) {
case 0:
return "no error, everything went ok";
case 1:
return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/
case 10:
return "end of input memory reached without huffman end code"; /*while huffman decoding*/
case 11:
return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/
case 13:
return "problem while processing dynamic deflate block";
case 14:
return "problem while processing dynamic deflate block";
case 15:
return "problem while processing dynamic deflate block";
/*this error could happen if there are only 0 or 1 symbols present in the huffman code:*/
case 16:
return "invalid code while processing dynamic deflate block";
case 17:
return "end of out buffer memory reached while inflating";
case 18:
return "invalid distance code while inflating";
case 19:
return "end of out buffer memory reached while inflating";
case 20:
return "invalid deflate block BTYPE encountered while decoding";
case 21:
return "NLEN is not ones complement of LEN in a deflate block";
/*end of out buffer memory reached while inflating:
This can happen if the inflated deflate data is longer than the amount of bytes required to fill up
all the pixels of the image, given the color depth and image dimensions. Something that doesn't
happen in a normal, well encoded, PNG image.*/
case 22:
return "end of out buffer memory reached while inflating";
case 23:
return "end of in buffer memory reached while inflating";
case 24:
return "invalid FCHECK in zlib header";
case 25:
return "invalid compression method in zlib header";
case 26:
return "FDICT encountered in zlib header while it's not used for PNG";
case 27:
return "PNG file is smaller than a PNG header";
/*Checks the magic file header, the first 8 bytes of the PNG file*/
case 28:
return "incorrect PNG signature, it's no PNG or corrupted";
case 29:
return "first chunk is not the header chunk";
case 30:
return "chunk length too large, chunk broken off at end of file";
case 31:
return "illegal PNG color type or bpp";
case 32:
return "illegal PNG compression method";
case 33:
return "illegal PNG filter method";
case 34:
return "illegal PNG interlace method";
case 35:
return "chunk length of a chunk is too large or the chunk too small";
case 36:
return "illegal PNG filter type encountered";
case 37:
return "illegal bit depth for this color type given";
case 38:
return "the palette is too small or too big"; /*0, or more than 256 colors*/
case 39:
return "tRNS chunk before PLTE or has more entries than palette size";
case 40:
return "tRNS chunk has wrong size for grayscale image";
case 41:
return "tRNS chunk has wrong size for RGB image";
case 42:
return "tRNS chunk appeared while it was not allowed for this color type";
case 43:
return "bKGD chunk has wrong size for palette image";
case 44:
return "bKGD chunk has wrong size for grayscale image";
case 45:
return "bKGD chunk has wrong size for RGB image";
case 48:
return "empty input buffer given to decoder. Maybe caused by non-existing file?";
case 49:
return "jumped past memory while generating dynamic huffman tree";
case 50:
return "jumped past memory while generating dynamic huffman tree";
case 51:
return "jumped past memory while inflating huffman block";
case 52:
return "jumped past memory while inflating";
case 53:
return "size of zlib data too small";
case 54:
return "repeat symbol in tree while there was no value symbol yet";
/*jumped past tree while generating huffman tree, this could be when the
tree will have more leaves than symbols after generating it out of the
given lengths. They call this an oversubscribed dynamic bit lengths tree in zlib.*/
case 55:
return "jumped past tree while generating huffman tree";
case 56:
return "given output image colortype or bitdepth not supported for color conversion";
case 57:
return "invalid CRC encountered (checking CRC can be disabled)";
case 58:
return "invalid ADLER32 encountered (checking ADLER32 can be disabled)";
case 59:
return "requested color conversion not supported";
case 60:
return "invalid window size given in the settings of the encoder (must be 0-32768)";
case 61:
return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)";
/*LodePNG leaves the choice of RGB to grayscale conversion formula to the user.*/
case 62:
return "conversion from color to grayscale not supported";
/*(2^31-1)*/
case 63:
return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk";
/*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/
case 64:
return "the length of the END symbol 256 in the Huffman tree is 0";
case 66:
return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes";
case 67:
return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";
case 68:
return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";
case 69:
return "unknown chunk type with 'critical' flag encountered by the decoder";
case 71:
return "invalid interlace mode given to encoder (must be 0 or 1)";
case 72:
return "while decoding, invalid compression method encountering in zTXt or iTXt chunk (it must be 0)";
case 73:
return "invalid tIME chunk size";
case 74:
return "invalid pHYs chunk size";
/*length could be wrong, or data chopped off*/
case 75:
return "no null termination char found while decoding text chunk";
case 76:
return "iTXt chunk too short to contain required bytes";
case 77:
return "integer overflow in buffer size";
case 78:
return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/
case 79:
return "failed to open file for writing";
case 80:
return "tried creating a tree of 0 symbols";
case 81:
return "lazy matching at pos 0 is impossible";
case 82:
return "color conversion to palette requested while a color isn't in palette, or index out of bounds";
case 83:
return "memory allocation failed";
case 84:
return "given image too small to contain all pixels to be encoded";
case 86:
return "impossible offset in lz77 encoding (internal bug)";
case 87:
return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";
case 88:
return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";
case 89:
return "text chunk keyword too short or long: must have size 1-79";
/*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/
case 90:
return "windowsize must be a power of two";
case 91:
return "invalid decompressed idat size";
case 92:
return "integer overflow due to too many pixels";
case 93:
return "zero width or height is invalid";
case 94:
return "header chunk must have a size of 13 bytes";
case 95:
return "integer overflow with combined idat chunk size";
case 96:
return "invalid gAMA chunk size";
case 97:
return "invalid cHRM chunk size";
case 98:
return "invalid sRGB chunk size";
case 99:
return "invalid sRGB rendering intent";
case 100:
return "invalid ICC profile color type, the PNG specification only allows RGB or GRAY";
case 101:
return "PNG specification does not allow RGB ICC profile on gray color types and vice versa";
case 102:
return "not allowed to set grayscale ICC profile with colored pixels by PNG specification";
case 103:
return "invalid palette index in bKGD chunk. Maybe it came before PLTE chunk?";
case 104:
return "invalid bKGD color while encoding (e.g. palette index out of range)";
case 105:
return "integer overflow of bitsize";
case 106:
return "PNG file must have PLTE chunk if color type is palette";
case 107:
return "color convert from palette mode requested without setting the palette data in it";
case 108:
return "tried to add more than 256 values to a palette";
/*this limit can be configured in LodePNGDecompressSettings*/
case 109:
return "tried to decompress zlib or deflate data larger than desired max_output_size";
case 110:
return "custom zlib or inflate decompression failed";
case 111:
return "custom zlib or deflate compression failed";
/*max text size limit can be configured in LodePNGDecoderSettings. This error prevents
unreasonable memory consumption when decoding due to impossibly large text sizes.*/
case 112:
return "compressed text unreasonably large";
/*max ICC size limit can be configured in LodePNGDecoderSettings. This error prevents
unreasonable memory consumption when decoding due to impossibly large ICC profile*/
case 113:
return "ICC profile unreasonably large";
}
return "unknown error code";
}
#endif /*LODEPNG_COMPILE_ERROR_TEXT*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // C++ Wrapper // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_CPP
namespace lodepng
{
#ifdef LODEPNG_COMPILE_DISK
unsigned load_file(std::vector<unsigned char> & buffer, const std::string & filename)
{
long size = lodepng_filesize(filename.c_str());
if(size < 0) return 78;
buffer.resize((size_t)size);
return size == 0 ? 0 : lodepng_buffer_file(&buffer[0], (size_t)size, filename.c_str());
}
/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
unsigned save_file(const std::vector<unsigned char> & buffer, const std::string & filename)
{
return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str());
}
#endif /* LODEPNG_COMPILE_DISK */
#ifdef LODEPNG_COMPILE_ZLIB
#ifdef LODEPNG_COMPILE_DECODER
unsigned decompress(std::vector<unsigned char> & out, const unsigned char * in, size_t insize,
const LodePNGDecompressSettings & settings)
{
unsigned char * buffer = 0;
size_t buffersize = 0;
unsigned error = zlib_decompress(&buffer, &buffersize, 0, in, insize, &settings);
if(buffer) {
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned decompress(std::vector<unsigned char> & out, const std::vector<unsigned char> & in,
const LodePNGDecompressSettings & settings)
{
return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings);
}
#endif /* LODEPNG_COMPILE_DECODER */
#ifdef LODEPNG_COMPILE_ENCODER
unsigned compress(std::vector<unsigned char> & out, const unsigned char * in, size_t insize,
const LodePNGCompressSettings & settings)
{
unsigned char * buffer = 0;
size_t buffersize = 0;
unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings);
if(buffer) {
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned compress(std::vector<unsigned char> & out, const std::vector<unsigned char> & in,
const LodePNGCompressSettings & settings)
{
return compress(out, in.empty() ? 0 : &in[0], in.size(), settings);
}
#endif /* LODEPNG_COMPILE_ENCODER */
#endif /* LODEPNG_COMPILE_ZLIB */
#ifdef LODEPNG_COMPILE_PNG
State::State()
{
lodepng_state_init(this);
}
State::State(const State & other)
{
lodepng_state_init(this);
lodepng_state_copy(this, &other);
}
State::~State()
{
lodepng_state_cleanup(this);
}
State & State::operator=(const State & other)
{
lodepng_state_copy(this, &other);
return *this;
}
#ifdef LODEPNG_COMPILE_DECODER
unsigned decode(std::vector<unsigned char> & out, unsigned & w, unsigned & h, const unsigned char * in,
size_t insize, LodePNGColorType colortype, unsigned bitdepth)
{
unsigned char * buffer = 0;
unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth);
if(buffer && !error) {
State state;
state.info_raw.colortype = colortype;
state.info_raw.bitdepth = bitdepth;
size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
}
lodepng_free(buffer);
return error;
}
unsigned decode(std::vector<unsigned char> & out, unsigned & w, unsigned & h,
const std::vector<unsigned char> & in, LodePNGColorType colortype, unsigned bitdepth)
{
return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth);
}
unsigned decode(std::vector<unsigned char> & out, unsigned & w, unsigned & h,
State & state,
const unsigned char * in, size_t insize)
{
unsigned char * buffer = NULL;
unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize);
if(buffer && !error) {
size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
}
lodepng_free(buffer);
return error;
}
unsigned decode(std::vector<unsigned char> & out, unsigned & w, unsigned & h,
State & state,
const std::vector<unsigned char> & in)
{
return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size());
}
#ifdef LODEPNG_COMPILE_DISK
unsigned decode(std::vector<unsigned char> & out, unsigned & w, unsigned & h, const std::string & filename,
LodePNGColorType colortype, unsigned bitdepth)
{
std::vector<unsigned char> buffer;
/* safe output values in case error happens */
w = h = 0;
unsigned error = load_file(buffer, filename);
if(error) return error;
return decode(out, w, h, buffer, colortype, bitdepth);
}
#endif /* LODEPNG_COMPILE_DECODER */
#endif /* LODEPNG_COMPILE_DISK */
#ifdef LODEPNG_COMPILE_ENCODER
unsigned encode(std::vector<unsigned char> & out, const unsigned char * in, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth)
{
unsigned char * buffer;
size_t buffersize;
unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth);
if(buffer) {
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned encode(std::vector<unsigned char> & out,
const std::vector<unsigned char> & in, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth)
{
if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
}
unsigned encode(std::vector<unsigned char> & out,
const unsigned char * in, unsigned w, unsigned h,
State & state)
{
unsigned char * buffer;
size_t buffersize;
unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state);
if(buffer) {
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned encode(std::vector<unsigned char> & out,
const std::vector<unsigned char> & in, unsigned w, unsigned h,
State & state)
{
if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84;
return encode(out, in.empty() ? 0 : &in[0], w, h, state);
}
#ifdef LODEPNG_COMPILE_DISK
unsigned encode(const std::string & filename,
const unsigned char * in, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth)
{
std::vector<unsigned char> buffer;
unsigned error = encode(buffer, in, w, h, colortype, bitdepth);
if(!error) error = save_file(buffer, filename);
return error;
}
unsigned encode(const std::string & filename,
const std::vector<unsigned char> & in, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth)
{
if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
}
#endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_ENCODER */
#endif /* LODEPNG_COMPILE_PNG */
} /* namespace lodepng */
#endif /*LODEPNG_COMPILE_CPP*/
#endif /*LV_USE_LODEPNG*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/gif/gifdec.c | #include "gifdec.h"
#include "../../misc/lv_log.h"
#include "../../stdlib/lv_mem.h"
#include "../../misc/lv_color.h"
#if LV_USE_GIF
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MIN(A, B) ((A) < (B) ? (A) : (B))
#define MAX(A, B) ((A) > (B) ? (A) : (B))
typedef struct Entry {
uint16_t length;
uint16_t prefix;
uint8_t suffix;
} Entry;
typedef struct Table {
int bulk;
int nentries;
Entry * entries;
} Table;
static gd_GIF * gif_open(gd_GIF * gif);
static bool f_gif_open(gd_GIF * gif, const void * path, bool is_file);
static void f_gif_read(gd_GIF * gif, void * buf, size_t len);
static int f_gif_seek(gd_GIF * gif, size_t pos, int k);
static void f_gif_close(gd_GIF * gif);
static uint16_t
read_num(gd_GIF * gif)
{
uint8_t bytes[2];
f_gif_read(gif, bytes, 2);
return bytes[0] + (((uint16_t) bytes[1]) << 8);
}
gd_GIF *
gd_open_gif_file(const char * fname)
{
gd_GIF gif_base;
memset(&gif_base, 0, sizeof(gif_base));
bool res = f_gif_open(&gif_base, fname, true);
if(!res) return NULL;
return gif_open(&gif_base);
}
gd_GIF *
gd_open_gif_data(const void * data)
{
gd_GIF gif_base;
memset(&gif_base, 0, sizeof(gif_base));
bool res = f_gif_open(&gif_base, data, false);
if(!res) return NULL;
return gif_open(&gif_base);
}
static gd_GIF * gif_open(gd_GIF * gif_base)
{
uint8_t sigver[3];
uint16_t width, height, depth;
uint8_t fdsz, bgidx, aspect;
int i;
uint8_t * bgcolor;
int gct_sz;
gd_GIF * gif = NULL;
/* Header */
f_gif_read(gif_base, sigver, 3);
if(memcmp(sigver, "GIF", 3) != 0) {
LV_LOG_WARN("invalid signature\n");
goto fail;
}
/* Version */
f_gif_read(gif_base, sigver, 3);
if(memcmp(sigver, "89a", 3) != 0) {
LV_LOG_WARN("invalid version\n");
goto fail;
}
/* Width x Height */
width = read_num(gif_base);
height = read_num(gif_base);
/* FDSZ */
f_gif_read(gif_base, &fdsz, 1);
/* Presence of GCT */
if(!(fdsz & 0x80)) {
LV_LOG_WARN("no global color table\n");
goto fail;
}
/* Color Space's Depth */
depth = ((fdsz >> 4) & 7) + 1;
/* Ignore Sort Flag. */
/* GCT Size */
gct_sz = 1 << ((fdsz & 0x07) + 1);
/* Background Color Index */
f_gif_read(gif_base, &bgidx, 1);
/* Aspect Ratio */
f_gif_read(gif_base, &aspect, 1);
/* Create gd_GIF Structure. */
#if LV_COLOR_DEPTH == 32 || LV_COLOR_DEPTH == 24
gif = lv_malloc(sizeof(gd_GIF) + 5 * width * height);
#elif LV_COLOR_DEPTH == 16
gif = lv_malloc(sizeof(gd_GIF) + 4 * width * height);
#elif LV_COLOR_DEPTH == 8
gif = lv_malloc(sizeof(gd_GIF) + 3 * width * height);
#endif
if(!gif) goto fail;
memcpy(gif, gif_base, sizeof(gd_GIF));
gif->width = width;
gif->height = height;
gif->depth = depth;
/* Read GCT */
gif->gct.size = gct_sz;
f_gif_read(gif, gif->gct.colors, 3 * gif->gct.size);
gif->palette = &gif->gct;
gif->bgindex = bgidx;
gif->canvas = (uint8_t *) &gif[1];
#if LV_COLOR_DEPTH == 32 || LV_COLOR_DEPTH == 24
gif->frame = &gif->canvas[4 * width * height];
#elif LV_COLOR_DEPTH == 16
gif->frame = &gif->canvas[3 * width * height];
#elif LV_COLOR_DEPTH == 8
gif->frame = &gif->canvas[2 * width * height];
#endif
if(gif->bgindex) {
memset(gif->frame, gif->bgindex, gif->width * gif->height);
}
bgcolor = &gif->palette->colors[gif->bgindex * 3];
for(i = 0; i < gif->width * gif->height; i++) {
#if LV_COLOR_DEPTH == 32 || LV_COLOR_DEPTH == 24
gif->canvas[i * 4 + 0] = *(bgcolor + 2);
gif->canvas[i * 4 + 1] = *(bgcolor + 1);
gif->canvas[i * 4 + 2] = *(bgcolor + 0);
gif->canvas[i * 4 + 3] = 0xff;
#elif LV_COLOR_DEPTH == 16
lv_color_t c = lv_color_make(*(bgcolor + 0), *(bgcolor + 1), *(bgcolor + 2));
uint16_t c16 = lv_color_to_int(c);
gif->canvas[i * 3 + 0] = c16 >> 8;
gif->canvas[i * 3 + 1] = c16 & 0xff;
gif->canvas[i * 3 + 2] = 0xff;
#elif LV_COLOR_DEPTH == 8
lv_color_t c = lv_color_make(*(bgcolor + 0), *(bgcolor + 1), *(bgcolor + 2));
gif->canvas[i * 2 + 0] = *((uint8_t *)&c);
gif->canvas[i * 2 + 1] = 0xff;
#endif
}
gif->anim_start = f_gif_seek(gif, 0, LV_FS_SEEK_CUR);
gif->loop_count = -1;
goto ok;
fail:
f_gif_close(gif_base);
ok:
return gif;
}
static void
discard_sub_blocks(gd_GIF * gif)
{
uint8_t size;
do {
f_gif_read(gif, &size, 1);
f_gif_seek(gif, size, LV_FS_SEEK_CUR);
} while(size);
}
static void
read_plain_text_ext(gd_GIF * gif)
{
if(gif->plain_text) {
uint16_t tx, ty, tw, th;
uint8_t cw, ch, fg, bg;
size_t sub_block;
f_gif_seek(gif, 1, LV_FS_SEEK_CUR); /* block size = 12 */
tx = read_num(gif);
ty = read_num(gif);
tw = read_num(gif);
th = read_num(gif);
f_gif_read(gif, &cw, 1);
f_gif_read(gif, &ch, 1);
f_gif_read(gif, &fg, 1);
f_gif_read(gif, &bg, 1);
sub_block = f_gif_seek(gif, 0, LV_FS_SEEK_CUR);
gif->plain_text(gif, tx, ty, tw, th, cw, ch, fg, bg);
f_gif_seek(gif, sub_block, LV_FS_SEEK_SET);
}
else {
/* Discard plain text metadata. */
f_gif_seek(gif, 13, LV_FS_SEEK_CUR);
}
/* Discard plain text sub-blocks. */
discard_sub_blocks(gif);
}
static void
read_graphic_control_ext(gd_GIF * gif)
{
uint8_t rdit;
/* Discard block size (always 0x04). */
f_gif_seek(gif, 1, LV_FS_SEEK_CUR);
f_gif_read(gif, &rdit, 1);
gif->gce.disposal = (rdit >> 2) & 3;
gif->gce.input = rdit & 2;
gif->gce.transparency = rdit & 1;
gif->gce.delay = read_num(gif);
f_gif_read(gif, &gif->gce.tindex, 1);
/* Skip block terminator. */
f_gif_seek(gif, 1, LV_FS_SEEK_CUR);
}
static void
read_comment_ext(gd_GIF * gif)
{
if(gif->comment) {
size_t sub_block = f_gif_seek(gif, 0, LV_FS_SEEK_CUR);
gif->comment(gif);
f_gif_seek(gif, sub_block, LV_FS_SEEK_SET);
}
/* Discard comment sub-blocks. */
discard_sub_blocks(gif);
}
static void
read_application_ext(gd_GIF * gif)
{
char app_id[8];
char app_auth_code[3];
uint16_t loop_count;
/* Discard block size (always 0x0B). */
f_gif_seek(gif, 1, LV_FS_SEEK_CUR);
/* Application Identifier. */
f_gif_read(gif, app_id, 8);
/* Application Authentication Code. */
f_gif_read(gif, app_auth_code, 3);
if(!strncmp(app_id, "NETSCAPE", sizeof(app_id))) {
/* Discard block size (0x03) and constant byte (0x01). */
f_gif_seek(gif, 2, LV_FS_SEEK_CUR);
loop_count = read_num(gif);
if(gif->loop_count < 0) {
if(loop_count == 0) {
gif->loop_count = 0;
}
else {
gif->loop_count = loop_count + 1;
}
}
/* Skip block terminator. */
f_gif_seek(gif, 1, LV_FS_SEEK_CUR);
}
else if(gif->application) {
size_t sub_block = f_gif_seek(gif, 0, LV_FS_SEEK_CUR);
gif->application(gif, app_id, app_auth_code);
f_gif_seek(gif, sub_block, LV_FS_SEEK_SET);
discard_sub_blocks(gif);
}
else {
discard_sub_blocks(gif);
}
}
static void
read_ext(gd_GIF * gif)
{
uint8_t label;
f_gif_read(gif, &label, 1);
switch(label) {
case 0x01:
read_plain_text_ext(gif);
break;
case 0xF9:
read_graphic_control_ext(gif);
break;
case 0xFE:
read_comment_ext(gif);
break;
case 0xFF:
read_application_ext(gif);
break;
default:
LV_LOG_WARN("unknown extension: %02X\n", label);
}
}
static Table *
new_table(int key_size)
{
int key;
int init_bulk = MAX(1 << (key_size + 1), 0x100);
Table * table = lv_malloc(sizeof(*table) + sizeof(Entry) * init_bulk);
if(table) {
table->bulk = init_bulk;
table->nentries = (1 << key_size) + 2;
table->entries = (Entry *) &table[1];
for(key = 0; key < (1 << key_size); key++)
table->entries[key] = (Entry) {
1, 0xFFF, key
};
}
return table;
}
/* Add table entry. Return value:
* 0 on success
* +1 if key size must be incremented after this addition
* -1 if could not realloc table */
static int
add_entry(Table ** tablep, uint16_t length, uint16_t prefix, uint8_t suffix)
{
Table * table = *tablep;
if(table->nentries == table->bulk) {
table->bulk *= 2;
table = lv_realloc(table, sizeof(*table) + sizeof(Entry) * table->bulk);
if(!table) return -1;
table->entries = (Entry *) &table[1];
*tablep = table;
}
table->entries[table->nentries] = (Entry) {
length, prefix, suffix
};
table->nentries++;
if((table->nentries & (table->nentries - 1)) == 0)
return 1;
return 0;
}
static uint16_t
get_key(gd_GIF * gif, int key_size, uint8_t * sub_len, uint8_t * shift, uint8_t * byte)
{
int bits_read;
int rpad;
int frag_size;
uint16_t key;
key = 0;
for(bits_read = 0; bits_read < key_size; bits_read += frag_size) {
rpad = (*shift + bits_read) % 8;
if(rpad == 0) {
/* Update byte. */
if(*sub_len == 0) {
f_gif_read(gif, sub_len, 1); /* Must be nonzero! */
if(*sub_len == 0) return 0x1000;
}
f_gif_read(gif, byte, 1);
(*sub_len)--;
}
frag_size = MIN(key_size - bits_read, 8 - rpad);
key |= ((uint16_t)((*byte) >> rpad)) << bits_read;
}
/* Clear extra bits to the left. */
key &= (1 << key_size) - 1;
*shift = (*shift + key_size) % 8;
return key;
}
/* Compute output index of y-th input line, in frame of height h. */
static int
interlaced_line_index(int h, int y)
{
int p; /* number of lines in current pass */
p = (h - 1) / 8 + 1;
if(y < p) /* pass 1 */
return y * 8;
y -= p;
p = (h - 5) / 8 + 1;
if(y < p) /* pass 2 */
return y * 8 + 4;
y -= p;
p = (h - 3) / 4 + 1;
if(y < p) /* pass 3 */
return y * 4 + 2;
y -= p;
/* pass 4 */
return y * 2 + 1;
}
/* Decompress image pixels.
* Return 0 on success or -1 on out-of-memory (w.r.t. LZW code table). */
static int
read_image_data(gd_GIF * gif, int interlace)
{
uint8_t sub_len, shift, byte;
int init_key_size, key_size, table_is_full = 0;
int frm_off, frm_size, str_len = 0, i, p, x, y;
uint16_t key, clear, stop;
int ret;
Table * table;
Entry entry = {0};
size_t start, end;
f_gif_read(gif, &byte, 1);
key_size = (int) byte;
start = f_gif_seek(gif, 0, LV_FS_SEEK_CUR);
discard_sub_blocks(gif);
end = f_gif_seek(gif, 0, LV_FS_SEEK_CUR);
f_gif_seek(gif, start, LV_FS_SEEK_SET);
clear = 1 << key_size;
stop = clear + 1;
table = new_table(key_size);
key_size++;
init_key_size = key_size;
sub_len = shift = 0;
key = get_key(gif, key_size, &sub_len, &shift, &byte); /* clear code */
frm_off = 0;
ret = 0;
frm_size = gif->fw * gif->fh;
while(frm_off < frm_size) {
if(key == clear) {
key_size = init_key_size;
table->nentries = (1 << (key_size - 1)) + 2;
table_is_full = 0;
}
else if(!table_is_full) {
ret = add_entry(&table, str_len + 1, key, entry.suffix);
if(ret == -1) {
lv_free(table);
return -1;
}
if(table->nentries == 0x1000) {
ret = 0;
table_is_full = 1;
}
}
key = get_key(gif, key_size, &sub_len, &shift, &byte);
if(key == clear) continue;
if(key == stop || key == 0x1000) break;
if(ret == 1) key_size++;
entry = table->entries[key];
str_len = entry.length;
for(i = 0; i < str_len; i++) {
p = frm_off + entry.length - 1;
x = p % gif->fw;
y = p / gif->fw;
if(interlace)
y = interlaced_line_index((int) gif->fh, y);
gif->frame[(gif->fy + y) * gif->width + gif->fx + x] = entry.suffix;
if(entry.prefix == 0xFFF)
break;
else
entry = table->entries[entry.prefix];
}
frm_off += str_len;
if(key < table->nentries - 1 && !table_is_full)
table->entries[table->nentries - 1].suffix = entry.suffix;
}
lv_free(table);
if(key == stop) f_gif_read(gif, &sub_len, 1); /* Must be zero! */
f_gif_seek(gif, end, LV_FS_SEEK_SET);
return 0;
}
/* Read image.
* Return 0 on success or -1 on out-of-memory (w.r.t. LZW code table). */
static int
read_image(gd_GIF * gif)
{
uint8_t fisrz;
int interlace;
/* Image Descriptor. */
gif->fx = read_num(gif);
gif->fy = read_num(gif);
gif->fw = read_num(gif);
gif->fh = read_num(gif);
f_gif_read(gif, &fisrz, 1);
interlace = fisrz & 0x40;
/* Ignore Sort Flag. */
/* Local Color Table? */
if(fisrz & 0x80) {
/* Read LCT */
gif->lct.size = 1 << ((fisrz & 0x07) + 1);
f_gif_read(gif, gif->lct.colors, 3 * gif->lct.size);
gif->palette = &gif->lct;
}
else
gif->palette = &gif->gct;
/* Image Data. */
return read_image_data(gif, interlace);
}
static void
render_frame_rect(gd_GIF * gif, uint8_t * buffer)
{
int i, j, k;
uint8_t index, * color;
i = gif->fy * gif->width + gif->fx;
for(j = 0; j < gif->fh; j++) {
for(k = 0; k < gif->fw; k++) {
index = gif->frame[(gif->fy + j) * gif->width + gif->fx + k];
color = &gif->palette->colors[index * 3];
if(!gif->gce.transparency || index != gif->gce.tindex) {
#if LV_COLOR_DEPTH == 32 || LV_COLOR_DEPTH == 24
buffer[(i + k) * 4 + 0] = *(color + 2);
buffer[(i + k) * 4 + 1] = *(color + 1);
buffer[(i + k) * 4 + 2] = *(color + 0);
buffer[(i + k) * 4 + 3] = 0xFF;
#elif LV_COLOR_DEPTH == 16
lv_color_t c = lv_color_make(*(color + 0), *(color + 1), *(color + 2));
uint16_t c16 = lv_color_to_int(c);
buffer[(i + k) * 3 + 0] = c16 & 0xff;
buffer[(i + k) * 3 + 1] = c16 >> 8;
buffer[(i + k) * 3 + 2] = 0xff;
#elif LV_COLOR_DEPTH == 8
lv_color_t c = lv_color_make(*(color + 0), *(color + 1), *(color + 2));
buffer[(i + k) * 2 + 0] = *((uint8_t *)&c);
buffer[(i + k) * 2 + 1] = 0xff;
#endif
}
}
i += gif->width;
}
}
static void
dispose(gd_GIF * gif)
{
int i, j, k;
uint8_t * bgcolor;
switch(gif->gce.disposal) {
case 2: /* Restore to background color. */
bgcolor = &gif->palette->colors[gif->bgindex * 3];
uint8_t opa = 0xff;
if(gif->gce.transparency) opa = 0x00;
i = gif->fy * gif->width + gif->fx;
for(j = 0; j < gif->fh; j++) {
for(k = 0; k < gif->fw; k++) {
#if LV_COLOR_DEPTH == 32 || LV_COLOR_DEPTH == 24
gif->canvas[(i + k) * 4 + 0] = *(bgcolor + 2);
gif->canvas[(i + k) * 4 + 1] = *(bgcolor + 1);
gif->canvas[(i + k) * 4 + 2] = *(bgcolor + 0);
gif->canvas[(i + k) * 4 + 3] = opa;
#elif LV_COLOR_DEPTH == 16
lv_color_t c = lv_color_make(*(bgcolor + 0), *(bgcolor + 1), *(bgcolor + 2));
uint16_t c16 = lv_color_to_int(c);
gif->canvas[(i + k) * 3 + 0] = c16 & 0xff;
gif->canvas[(i + k) * 3 + 1] = c16 >> 8;
gif->canvas[(i + k) * 3 + 2] = opa;
#elif LV_COLOR_DEPTH == 8
lv_color_t c = lv_color_make(*(bgcolor + 0), *(bgcolor + 1), *(bgcolor + 2));
gif->canvas[(i + k) * 2 + 0] = *((uint8_t *)&c);
gif->canvas[(i + k) * 2 + 1] = opa;
#endif
}
i += gif->width;
}
break;
case 3: /* Restore to previous, i.e., don't update canvas.*/
break;
default:
/* Add frame non-transparent pixels to canvas. */
render_frame_rect(gif, gif->canvas);
}
}
/* Return 1 if got a frame; 0 if got GIF trailer; -1 if error. */
int
gd_get_frame(gd_GIF * gif)
{
char sep;
dispose(gif);
f_gif_read(gif, &sep, 1);
while(sep != ',') {
if(sep == ';') {
f_gif_seek(gif, gif->anim_start, LV_FS_SEEK_SET);
if(gif->loop_count == 1 || gif->loop_count < 0) {
return 0;
}
else if(gif->loop_count > 1) {
gif->loop_count--;
}
}
else if(sep == '!')
read_ext(gif);
else return -1;
f_gif_read(gif, &sep, 1);
}
if(read_image(gif) == -1)
return -1;
return 1;
}
void
gd_render_frame(gd_GIF * gif, uint8_t * buffer)
{
render_frame_rect(gif, buffer);
}
void
gd_rewind(gd_GIF * gif)
{
gif->loop_count = -1;
f_gif_seek(gif, gif->anim_start, LV_FS_SEEK_SET);
}
void
gd_close_gif(gd_GIF * gif)
{
f_gif_close(gif);
lv_free(gif);
}
static bool f_gif_open(gd_GIF * gif, const void * path, bool is_file)
{
gif->f_rw_p = 0;
gif->data = NULL;
gif->is_file = is_file;
if(is_file) {
lv_fs_res_t res = lv_fs_open(&gif->fd, path, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) return false;
else return true;
}
else {
gif->data = path;
return true;
}
}
static void f_gif_read(gd_GIF * gif, void * buf, size_t len)
{
if(gif->is_file) {
lv_fs_read(&gif->fd, buf, len, NULL);
}
else {
memcpy(buf, &gif->data[gif->f_rw_p], len);
gif->f_rw_p += len;
}
}
static int f_gif_seek(gd_GIF * gif, size_t pos, int k)
{
if(gif->is_file) {
lv_fs_seek(&gif->fd, pos, k);
uint32_t x;
lv_fs_tell(&gif->fd, &x);
return x;
}
else {
if(k == LV_FS_SEEK_CUR) gif->f_rw_p += pos;
else if(k == LV_FS_SEEK_SET) gif->f_rw_p = pos;
return gif->f_rw_p;
}
}
static void f_gif_close(gd_GIF * gif)
{
if(gif->is_file) {
lv_fs_close(&gif->fd);
}
}
#endif /*LV_USE_GIF*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/gif/lv_gif.c | /**
* @file lv_gifenc.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_gif.h"
#if LV_USE_GIF
#include "gifdec.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_gif_class
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_gif_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_gif_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void next_frame_task_cb(lv_timer_t * t);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_gif_class = {
.constructor_cb = lv_gif_constructor,
.destructor_cb = lv_gif_destructor,
.instance_size = sizeof(lv_gif_t),
.base_class = &lv_image_class,
.name = "gif",
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_gif_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;
}
void lv_gif_set_src(lv_obj_t * obj, const void * src)
{
lv_gif_t * gifobj = (lv_gif_t *) obj;
/*Close previous gif if any*/
if(gifobj->gif) {
lv_cache_lock();
lv_cache_invalidate(lv_cache_find(lv_image_get_src(obj), LV_CACHE_SRC_TYPE_PTR, 0, 0));
lv_cache_unlock();
gd_close_gif(gifobj->gif);
gifobj->gif = NULL;
gifobj->imgdsc.data = NULL;
}
if(lv_image_src_get_type(src) == LV_IMAGE_SRC_VARIABLE) {
const lv_image_dsc_t * img_dsc = src;
gifobj->gif = gd_open_gif_data(img_dsc->data);
}
else if(lv_image_src_get_type(src) == LV_IMAGE_SRC_FILE) {
gifobj->gif = gd_open_gif_file(src);
}
if(gifobj->gif == NULL) {
LV_LOG_WARN("Couldn't load the source");
return;
}
gifobj->imgdsc.data = gifobj->gif->canvas;
gifobj->imgdsc.header.always_zero = 0;
gifobj->imgdsc.header.cf = LV_COLOR_FORMAT_NATIVE_WITH_ALPHA;
gifobj->imgdsc.header.h = gifobj->gif->height;
gifobj->imgdsc.header.w = gifobj->gif->width;
gifobj->last_call = lv_tick_get();
lv_image_set_src(obj, &gifobj->imgdsc);
lv_timer_resume(gifobj->timer);
lv_timer_reset(gifobj->timer);
next_frame_task_cb(gifobj->timer);
}
void lv_gif_restart(lv_obj_t * obj)
{
lv_gif_t * gifobj = (lv_gif_t *) obj;
gd_rewind(gifobj->gif);
lv_timer_resume(gifobj->timer);
lv_timer_reset(gifobj->timer);
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_gif_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_gif_t * gifobj = (lv_gif_t *) obj;
gifobj->gif = NULL;
gifobj->timer = lv_timer_create(next_frame_task_cb, 10, obj);
lv_timer_pause(gifobj->timer);
}
static void lv_gif_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_gif_t * gifobj = (lv_gif_t *) obj;
lv_cache_lock();
lv_cache_invalidate(lv_cache_find(lv_image_get_src(obj), LV_CACHE_SRC_TYPE_PTR, 0, 0));
lv_cache_unlock();
if(gifobj->gif)
gd_close_gif(gifobj->gif);
lv_timer_delete(gifobj->timer);
}
static void next_frame_task_cb(lv_timer_t * t)
{
lv_obj_t * obj = t->user_data;
lv_gif_t * gifobj = (lv_gif_t *) obj;
uint32_t elaps = lv_tick_elaps(gifobj->last_call);
if(elaps < gifobj->gif->gce.delay * 10) return;
gifobj->last_call = lv_tick_get();
int has_next = gd_get_frame(gifobj->gif);
if(has_next == 0) {
/*It was the last repeat*/
lv_result_t res = lv_obj_send_event(obj, LV_EVENT_READY, NULL);
lv_timer_pause(t);
if(res != LV_FS_RES_OK) return;
}
gd_render_frame(gifobj->gif, (uint8_t *)gifobj->imgdsc.data);
lv_cache_lock();
lv_cache_invalidate(lv_cache_find(lv_image_get_src(obj), LV_CACHE_SRC_TYPE_PTR, 0, 0));
lv_cache_unlock();
lv_obj_invalidate(obj);
}
#endif /*LV_USE_GIF*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/gif/gifdec.h | #ifndef GIFDEC_H
#define GIFDEC_H
#include <stdint.h>
#include "../../misc/lv_fs.h"
#if LV_USE_GIF
typedef struct _gd_Palette {
int size;
uint8_t colors[0x100 * 3];
} gd_Palette;
typedef struct _gd_GCE {
uint16_t delay;
uint8_t tindex;
uint8_t disposal;
int input;
int transparency;
} gd_GCE;
typedef struct _gd_GIF {
lv_fs_file_t fd;
const char * data;
uint8_t is_file;
uint32_t f_rw_p;
int32_t anim_start;
uint16_t width, height;
uint16_t depth;
int32_t loop_count;
gd_GCE gce;
gd_Palette * palette;
gd_Palette lct, gct;
void (*plain_text)(
struct _gd_GIF * gif, uint16_t tx, uint16_t ty,
uint16_t tw, uint16_t th, uint8_t cw, uint8_t ch,
uint8_t fg, uint8_t bg
);
void (*comment)(struct _gd_GIF * gif);
void (*application)(struct _gd_GIF * gif, char id[8], char auth[3]);
uint16_t fx, fy, fw, fh;
uint8_t bgindex;
uint8_t * canvas, * frame;
} gd_GIF;
gd_GIF * gd_open_gif_file(const char * fname);
gd_GIF * gd_open_gif_data(const void * data);
void gd_render_frame(gd_GIF * gif, uint8_t * buffer);
int gd_get_frame(gd_GIF * gif);
void gd_rewind(gd_GIF * gif);
void gd_close_gif(gd_GIF * gif);
#endif /*LV_USE_GIF*/
#endif /* GIFDEC_H */
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/gif/lv_gif.h | /**
* @file lv_gif.h
*
*/
#ifndef LV_GIF_H
#define LV_GIF_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_GIF
#include "gifdec.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_image_t img;
gd_GIF * gif;
lv_timer_t * timer;
lv_image_dsc_t imgdsc;
uint32_t last_call;
} lv_gif_t;
extern const lv_obj_class_t lv_gif_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
lv_obj_t * lv_gif_create(lv_obj_t * parent);
void lv_gif_set_src(lv_obj_t * obj, const void * src);
void lv_gif_restart(lv_obj_t * gif);
/**********************
* MACROS
**********************/
#endif /*LV_USE_GIF*/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*LV_GIF_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/rlottie/lv_rlottie.c | /**
* @file lv_rlottie.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_rlottie.h"
#if LV_USE_RLOTTIE
#include <rlottie_capi.h>
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_rlottie_class
#define LV_ARGB32 32
/**********************
* TYPEDEFS
**********************/
#define LV_ARGB32 32
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_rlottie_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_rlottie_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void next_frame_task_cb(lv_timer_t * t);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_rlottie_class = {
.constructor_cb = lv_rlottie_constructor,
.destructor_cb = lv_rlottie_destructor,
.instance_size = sizeof(lv_rlottie_t),
.base_class = &lv_image_class,
.name = "rlottie",
};
typedef struct {
int32_t width;
int32_t height;
const char * rlottie_desc;
const char * path;
} lv_rlottie_create_info_t;
// only used in lv_obj_class_create_obj, no affect multiple instances
static lv_rlottie_create_info_t create_info;
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_rlottie_create_from_file(lv_obj_t * parent, int32_t width, int32_t height, const char * path)
{
create_info.width = width;
create_info.height = height;
create_info.path = path;
create_info.rlottie_desc = NULL;
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
lv_obj_t * lv_rlottie_create_from_raw(lv_obj_t * parent, int32_t width, int32_t height, const char * rlottie_desc)
{
create_info.width = width;
create_info.height = height;
create_info.rlottie_desc = rlottie_desc;
create_info.path = NULL;
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
void lv_rlottie_set_play_mode(lv_obj_t * obj, const lv_rlottie_ctrl_t ctrl)
{
lv_rlottie_t * rlottie = (lv_rlottie_t *) obj;
rlottie->play_ctrl = ctrl;
if(rlottie->task && (rlottie->dest_frame != rlottie->current_frame ||
(rlottie->play_ctrl & LV_RLOTTIE_CTRL_PAUSE) == LV_RLOTTIE_CTRL_PLAY)) {
lv_timer_resume(rlottie->task);
}
}
void lv_rlottie_set_current_frame(lv_obj_t * obj, const size_t goto_frame)
{
lv_rlottie_t * rlottie = (lv_rlottie_t *) obj;
rlottie->current_frame = goto_frame < rlottie->total_frames ? goto_frame : rlottie->total_frames - 1;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_rlottie_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_rlottie_t * rlottie = (lv_rlottie_t *) obj;
if(create_info.rlottie_desc) {
rlottie->animation = lottie_animation_from_data(create_info.rlottie_desc, create_info.rlottie_desc, "");
}
else if(create_info.path) {
rlottie->animation = lottie_animation_from_file(create_info.path);
}
if(rlottie->animation == NULL) {
LV_LOG_WARN("The aniamtion can't be opened");
return;
}
rlottie->total_frames = lottie_animation_get_totalframe(rlottie->animation);
rlottie->framerate = (size_t)lottie_animation_get_framerate(rlottie->animation);
rlottie->current_frame = 0;
rlottie->scanline_width = create_info.width * LV_ARGB32 / 8;
size_t allocaled_buf_size = (create_info.width * create_info.height * LV_ARGB32 / 8);
rlottie->allocated_buf = lv_malloc(allocaled_buf_size);
if(rlottie->allocated_buf != NULL) {
rlottie->allocated_buffer_size = allocaled_buf_size;
memset(rlottie->allocated_buf, 0, allocaled_buf_size);
}
rlottie->imgdsc.header.always_zero = 0;
rlottie->imgdsc.header.cf = LV_COLOR_FORMAT_ARGB8888;
rlottie->imgdsc.header.h = create_info.height;
rlottie->imgdsc.header.w = create_info.width;
rlottie->imgdsc.data = (void *)rlottie->allocated_buf;
rlottie->imgdsc.data_size = allocaled_buf_size;
lv_image_set_src(obj, &rlottie->imgdsc);
rlottie->play_ctrl = LV_RLOTTIE_CTRL_FORWARD | LV_RLOTTIE_CTRL_PLAY | LV_RLOTTIE_CTRL_LOOP;
rlottie->dest_frame = rlottie->total_frames; /* invalid destination frame so it's possible to pause on frame 0 */
rlottie->task = lv_timer_create(next_frame_task_cb, 1000 / rlottie->framerate, obj);
lv_obj_update_layout(obj);
}
static void lv_rlottie_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_rlottie_t * rlottie = (lv_rlottie_t *) obj;
if(rlottie->animation) {
lottie_animation_destroy(rlottie->animation);
rlottie->animation = 0;
rlottie->current_frame = 0;
rlottie->framerate = 0;
rlottie->scanline_width = 0;
rlottie->total_frames = 0;
}
if(rlottie->task) {
lv_timer_delete(rlottie->task);
rlottie->task = NULL;
rlottie->play_ctrl = LV_RLOTTIE_CTRL_FORWARD;
rlottie->dest_frame = 0;
}
lv_cache_lock();
lv_cache_invalidate(lv_cache_find(&rlottie->imgdsc, LV_CACHE_SRC_TYPE_PTR, 0, 0));
lv_cache_unlock();
if(rlottie->allocated_buf) {
lv_free(rlottie->allocated_buf);
rlottie->allocated_buf = NULL;
rlottie->allocated_buffer_size = 0;
}
}
static void next_frame_task_cb(lv_timer_t * t)
{
lv_obj_t * obj = t->user_data;
lv_rlottie_t * rlottie = (lv_rlottie_t *) obj;
if((rlottie->play_ctrl & LV_RLOTTIE_CTRL_PAUSE) == LV_RLOTTIE_CTRL_PAUSE) {
if(rlottie->current_frame == rlottie->dest_frame) {
/* Pause the timer too when it has run once to avoid CPU consumption */
lv_timer_pause(t);
return;
}
rlottie->dest_frame = rlottie->current_frame;
}
else {
if((rlottie->play_ctrl & LV_RLOTTIE_CTRL_BACKWARD) == LV_RLOTTIE_CTRL_BACKWARD) {
if(rlottie->current_frame > 0)
--rlottie->current_frame;
else { /* Looping ? */
if((rlottie->play_ctrl & LV_RLOTTIE_CTRL_LOOP) == LV_RLOTTIE_CTRL_LOOP)
rlottie->current_frame = rlottie->total_frames - 1;
else {
lv_obj_send_event(obj, LV_EVENT_READY, NULL);
lv_timer_pause(t);
return;
}
}
}
else {
if(rlottie->current_frame < rlottie->total_frames)
++rlottie->current_frame;
else { /* Looping ? */
if((rlottie->play_ctrl & LV_RLOTTIE_CTRL_LOOP) == LV_RLOTTIE_CTRL_LOOP)
rlottie->current_frame = 0;
else {
lv_obj_send_event(obj, LV_EVENT_READY, NULL);
lv_timer_pause(t);
return;
}
}
}
}
lottie_animation_render(
rlottie->animation,
rlottie->current_frame,
rlottie->allocated_buf,
rlottie->imgdsc.header.w,
rlottie->imgdsc.header.h,
rlottie->scanline_width
);
lv_obj_invalidate(obj);
}
#endif /*LV_USE_RLOTTIE*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/rlottie/lv_rlottie.h | /**
* @file lv_rlottie.h
*
*/
#ifndef LV_RLOTTIE_H
#define LV_RLOTTIE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_RLOTTIE
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef enum {
LV_RLOTTIE_CTRL_FORWARD = 0,
LV_RLOTTIE_CTRL_BACKWARD = 1,
LV_RLOTTIE_CTRL_PAUSE = 2,
LV_RLOTTIE_CTRL_PLAY = 0, /* Yes, play = 0 is the default mode */
LV_RLOTTIE_CTRL_LOOP = 8,
} lv_rlottie_ctrl_t;
/** definition in lottieanimation_capi.c */
struct Lottie_Animation_S;
typedef struct {
lv_image_t img_ext;
struct Lottie_Animation_S * animation;
lv_timer_t * task;
lv_image_dsc_t imgdsc;
size_t total_frames;
size_t current_frame;
size_t framerate;
uint32_t * allocated_buf;
size_t allocated_buffer_size;
size_t scanline_width;
lv_rlottie_ctrl_t play_ctrl;
size_t dest_frame;
} lv_rlottie_t;
extern const lv_obj_class_t lv_rlottie_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
lv_obj_t * lv_rlottie_create_from_file(lv_obj_t * parent, int32_t width, int32_t height, const char * path);
lv_obj_t * lv_rlottie_create_from_raw(lv_obj_t * parent, int32_t width, int32_t height,
const char * rlottie_desc);
void lv_rlottie_set_play_mode(lv_obj_t * rlottie, const lv_rlottie_ctrl_t ctrl);
void lv_rlottie_set_current_frame(lv_obj_t * rlottie, const size_t goto_frame);
/**********************
* MACROS
**********************/
#endif /*LV_USE_RLOTTIE*/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*LV_RLOTTIE_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/tiny_ttf/stb_rect_pack.h | // stb_rect_pack.h - v1.01 - public domain - rectangle packing
// Sean Barrett 2014
//
// Useful for e.g. packing rectangular textures into an atlas.
// Does not do rotation.
//
// Before #including,
//
// #define STB_RECT_PACK_IMPLEMENTATION
//
// in the file that you want to have the implementation.
//
// Not necessarily the awesomest packing method, but better than
// the totally naive one in stb_truetype (which is primarily what
// this is meant to replace).
//
// Has only had a few tests run, may have issues.
//
// More docs to come.
//
// No memory allocations; uses qsort() and assert() from stdlib.
// Can override those by defining STBRP_SORT and STBRP_ASSERT.
//
// This library currently uses the Skyline Bottom-Left algorithm.
//
// Please note: better rectangle packers are welcome! Please
// implement them to the same API, but with a different init
// function.
//
// Credits
//
// Library
// Sean Barrett
// Minor features
// Martins Mozeiko
// github:IntellectualKitty
//
// Bugfixes / warning fixes
// Jeremy Jaussaud
// Fabian Giesen
//
// Version history:
//
// 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section
// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles
// 0.99 (2019-02-07) warning fixes
// 0.11 (2017-03-03) return packing success/fail result
// 0.10 (2016-10-25) remove cast-away-const to avoid warnings
// 0.09 (2016-08-27) fix compiler warnings
// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
// 0.05: added STBRP_ASSERT to allow replacing assert
// 0.04: fixed minor bug in STBRP_LARGE_RECTS support
// 0.01: initial release
//
// LICENSE
//
// See end of file for license information.
//////////////////////////////////////////////////////////////////////////////
//
// INCLUDE SECTION
//
#ifndef STB_INCLUDE_STB_RECT_PACK_H
#define STB_INCLUDE_STB_RECT_PACK_H
#define STB_RECT_PACK_VERSION 1
#ifdef STBRP_STATIC
#define STBRP_DEF static
#else
#define STBRP_DEF extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
/// @cond
/**
* Tells Doxygen to ignore a duplicate declaration
*/
typedef struct stbrp_context stbrp_context;
typedef struct stbrp_node stbrp_node;
typedef struct stbrp_rect stbrp_rect;
/// @endcond
typedef int stbrp_coord;
#define STBRP__MAXVAL 0x7fffffff
// Mostly for internal use, but this is the maximum supported coordinate value.
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function"
#endif
STBRP_DEF int stbrp_pack_rects(stbrp_context * context, stbrp_rect * rects, int num_rects);
// Assign packed locations to rectangles. The rectangles are of type
// 'stbrp_rect' defined below, stored in the array 'rects', and there
// are 'num_rects' many of them.
//
// Rectangles which are successfully packed have the 'was_packed' flag
// set to a non-zero value and 'x' and 'y' store the minimum location
// on each axis (i.e. bottom-left in cartesian coordinates, top-left
// if you imagine y increasing downwards). Rectangles which do not fit
// have the 'was_packed' flag set to 0.
//
// You should not try to access the 'rects' array from another thread
// while this function is running, as the function temporarily reorders
// the array while it executes.
//
// To pack into another rectangle, you need to call stbrp_init_target
// again. To continue packing into the same rectangle, you can call
// this function again. Calling this multiple times with multiple rect
// arrays will probably produce worse packing results than calling it
// a single time with the full rectangle array, but the option is
// available.
//
// The function returns 1 if all of the rectangles were successfully
// packed and 0 otherwise.
struct stbrp_rect {
// reserved for your use:
int id;
// input:
stbrp_coord w, h;
// output:
stbrp_coord x, y;
int was_packed; // non-zero if valid packing
}; // 16 bytes, nominally
STBRP_DEF void stbrp_init_target(stbrp_context * context, int width, int height, stbrp_node * nodes, int num_nodes);
// Initialize a rectangle packer to:
// pack a rectangle that is 'width' by 'height' in dimensions
// using temporary storage provided by the array 'nodes', which is 'num_nodes' long
//
// You must call this function every time you start packing into a new target.
//
// There is no "shutdown" function. The 'nodes' memory must stay valid for
// the following stbrp_pack_rects() call (or calls), but can be freed after
// the call (or calls) finish.
//
// Note: to guarantee best results, either:
// 1. make sure 'num_nodes' >= 'width'
// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
//
// If you don't do either of the above things, widths will be quantized to multiples
// of small integers to guarantee the algorithm doesn't run out of temporary storage.
//
// If you do #2, then the non-quantized algorithm will be used, but the algorithm
// may run out of temporary storage and be unable to pack some rectangles.
STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context * context, int allow_out_of_mem);
// Optionally call this function after init but before doing any packing to
// change the handling of the out-of-temp-memory scenario, described above.
// If you call init again, this will be reset to the default (false).
STBRP_DEF void stbrp_setup_heuristic(stbrp_context * context, int heuristic);
// Optionally select which packing heuristic the library should use. Different
// heuristics will produce better/worse results for different data sets.
// If you call init again, this will be reset to the default.
enum {
STBRP_HEURISTIC_Skyline_default = 0,
STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
STBRP_HEURISTIC_Skyline_BF_sortHeight
};
//////////////////////////////////////////////////////////////////////////////
//
// the details of the following structures don't matter to you, but they must
// be visible so you can handle the memory allocations for them
struct stbrp_node {
stbrp_coord x, y;
stbrp_node * next;
};
struct stbrp_context {
int width;
int height;
int align;
int init_mode;
int heuristic;
int num_nodes;
stbrp_node * active_head;
stbrp_node * free_head;
stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
};
#ifdef __cplusplus
}
#endif
#endif
//////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION SECTION
//
#ifdef STB_RECT_PACK_IMPLEMENTATION
#ifndef STBRP_SORT
#include <stdlib.h>
#define STBRP_SORT qsort
#endif
#ifndef STBRP_ASSERT
#include <assert.h>
#define STBRP_ASSERT assert
#endif
#ifdef _MSC_VER
#define STBRP__NOTUSED(v) (void)(v)
#define STBRP__CDECL __cdecl
#else
#define STBRP__NOTUSED(v) (void)sizeof(v)
#define STBRP__CDECL
#endif
enum {
STBRP__INIT_skyline = 1
};
STBRP_DEF void stbrp_setup_heuristic(stbrp_context * context, int heuristic)
{
switch(context->init_mode) {
case STBRP__INIT_skyline:
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
context->heuristic = heuristic;
break;
default:
STBRP_ASSERT(0);
}
}
STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context * context, int allow_out_of_mem)
{
if(allow_out_of_mem)
// if it's ok to run out of memory, then don't bother aligning them;
// this gives better packing, but may fail due to OOM (even though
// the rectangles easily fit). @TODO a smarter approach would be to only
// quantize once we've hit OOM, then we could get rid of this parameter.
context->align = 1;
else {
// if it's not ok to run out of memory, then quantize the widths
// so that num_nodes is always enough nodes.
//
// I.e. num_nodes * align >= width
// align >= width / num_nodes
// align = ceil(width/num_nodes)
context->align = (context->width + context->num_nodes - 1) / context->num_nodes;
}
}
STBRP_DEF void stbrp_init_target(stbrp_context * context, int width, int height, stbrp_node * nodes, int num_nodes)
{
int i;
for(i = 0; i < num_nodes - 1; ++i)
nodes[i].next = &nodes[i + 1];
nodes[i].next = NULL;
context->init_mode = STBRP__INIT_skyline;
context->heuristic = STBRP_HEURISTIC_Skyline_default;
context->free_head = &nodes[0];
context->active_head = &context->extra[0];
context->width = width;
context->height = height;
context->num_nodes = num_nodes;
stbrp_setup_allow_out_of_mem(context, 0);
// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
context->extra[0].x = 0;
context->extra[0].y = 0;
context->extra[0].next = &context->extra[1];
context->extra[1].x = (stbrp_coord) width;
context->extra[1].y = (1 << 30);
context->extra[1].next = NULL;
}
// find minimum y position if it starts at x1
static int stbrp__skyline_find_min_y(stbrp_context * c, stbrp_node * first, int x0, int width, int * pwaste)
{
stbrp_node * node = first;
int x1 = x0 + width;
int min_y, visited_width, waste_area;
STBRP__NOTUSED(c);
STBRP_ASSERT(first->x <= x0);
#if 0
// skip in case we're past the node
while(node->next->x <= x0)
++node;
#else
STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
#endif
STBRP_ASSERT(node->x <= x0);
min_y = 0;
waste_area = 0;
visited_width = 0;
while(node->x < x1) {
if(node->y > min_y) {
// raise min_y higher.
// we've accounted for all waste up to min_y,
// but we'll now add more waste for everything we've visited
waste_area += visited_width * (node->y - min_y);
min_y = node->y;
// the first time through, visited_width might be reduced
if(node->x < x0)
visited_width += node->next->x - x0;
else
visited_width += node->next->x - node->x;
}
else {
// add waste area
int under_width = node->next->x - node->x;
if(under_width + visited_width > width)
under_width = width - visited_width;
waste_area += under_width * (min_y - node->y);
visited_width += under_width;
}
node = node->next;
}
*pwaste = waste_area;
return min_y;
}
typedef struct {
int x, y;
stbrp_node ** prev_link;
} stbrp__findresult;
static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context * c, int width, int height)
{
int best_waste = (1 << 30), best_x, best_y = (1 << 30);
stbrp__findresult fr;
stbrp_node ** prev, * node, * tail, ** best = NULL;
// align to multiple of c->align
width = (width + c->align - 1);
width -= width % c->align;
STBRP_ASSERT(width % c->align == 0);
// if it can't possibly fit, bail immediately
if(width > c->width || height > c->height) {
fr.prev_link = NULL;
fr.x = fr.y = 0;
return fr;
}
node = c->active_head;
prev = &c->active_head;
while(node->x + width <= c->width) {
int y, waste;
y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
if(c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
// bottom left
if(y < best_y) {
best_y = y;
best = prev;
}
}
else {
// best-fit
if(y + height <= c->height) {
// can only use it if it first vertically
if(y < best_y || (y == best_y && waste < best_waste)) {
best_y = y;
best_waste = waste;
best = prev;
}
}
}
prev = &node->next;
node = node->next;
}
best_x = (best == NULL) ? 0 : (*best)->x;
// if doing best-fit (BF), we also have to try aligning right edge to each node position
//
// e.g, if fitting
//
// ____________________
// |____________________|
//
// into
//
// | |
// | ____________|
// |____________|
//
// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
//
// This makes BF take about 2x the time
if(c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
tail = c->active_head;
node = c->active_head;
prev = &c->active_head;
// find first node that's admissible
while(tail->x < width)
tail = tail->next;
while(tail) {
int xpos = tail->x - width;
int y, waste;
STBRP_ASSERT(xpos >= 0);
// find the left position that matches this
while(node->next->x <= xpos) {
prev = &node->next;
node = node->next;
}
STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
if(y + height <= c->height) {
if(y <= best_y) {
if(y < best_y || waste < best_waste || (waste == best_waste && xpos < best_x)) {
best_x = xpos;
STBRP_ASSERT(y <= best_y);
best_y = y;
best_waste = waste;
best = prev;
}
}
}
tail = tail->next;
}
}
fr.prev_link = best;
fr.x = best_x;
fr.y = best_y;
return fr;
}
static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context * context, int width, int height)
{
// find best position according to heuristic
stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
stbrp_node * node, * cur;
// bail if:
// 1. it failed
// 2. the best node doesn't fit (we don't always check this)
// 3. we're out of memory
if(res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
res.prev_link = NULL;
return res;
}
// on success, create new node
node = context->free_head;
node->x = (stbrp_coord) res.x;
node->y = (stbrp_coord)(res.y + height);
context->free_head = node->next;
// insert the new node into the right starting point, and
// let 'cur' point to the remaining nodes needing to be
// stiched back in
cur = *res.prev_link;
if(cur->x < res.x) {
// preserve the existing one, so start testing with the next one
stbrp_node * next = cur->next;
cur->next = node;
cur = next;
}
else {
*res.prev_link = node;
}
// from here, traverse cur and free the nodes, until we get to one
// that shouldn't be freed
while(cur->next && cur->next->x <= res.x + width) {
stbrp_node * next = cur->next;
// move the current node to the free list
cur->next = context->free_head;
context->free_head = cur;
cur = next;
}
// stitch the list back in
node->next = cur;
if(cur->x < res.x + width)
cur->x = (stbrp_coord)(res.x + width);
#ifdef _DEBUG
cur = context->active_head;
while(cur->x < context->width) {
STBRP_ASSERT(cur->x < cur->next->x);
cur = cur->next;
}
STBRP_ASSERT(cur->next == NULL);
{
int count = 0;
cur = context->active_head;
while(cur) {
cur = cur->next;
++count;
}
cur = context->free_head;
while(cur) {
cur = cur->next;
++count;
}
STBRP_ASSERT(count == context->num_nodes + 2);
}
#endif
return res;
}
static int STBRP__CDECL rect_height_compare(const void * a, const void * b)
{
const stbrp_rect * p = (const stbrp_rect *) a;
const stbrp_rect * q = (const stbrp_rect *) b;
if(p->h > q->h)
return -1;
if(p->h < q->h)
return 1;
return (p->w > q->w) ? -1 : (p->w < q->w);
}
static int STBRP__CDECL rect_original_order(const void * a, const void * b)
{
const stbrp_rect * p = (const stbrp_rect *) a;
const stbrp_rect * q = (const stbrp_rect *) b;
return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
}
STBRP_DEF int stbrp_pack_rects(stbrp_context * context, stbrp_rect * rects, int num_rects)
{
int i, all_rects_packed = 1;
// we use the 'was_packed' field internally to allow sorting/unsorting
for(i = 0; i < num_rects; ++i) {
rects[i].was_packed = i;
}
// sort according to heuristic
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
for(i = 0; i < num_rects; ++i) {
if(rects[i].w == 0 || rects[i].h == 0) {
rects[i].x = rects[i].y = 0; // empty rect needs no space
}
else {
stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
if(fr.prev_link) {
rects[i].x = (stbrp_coord) fr.x;
rects[i].y = (stbrp_coord) fr.y;
}
else {
rects[i].x = rects[i].y = STBRP__MAXVAL;
}
}
}
// unsort
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
// set was_packed flags and all_rects_packed status
for(i = 0; i < num_rects; ++i) {
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
if(!rects[i].was_packed)
all_rects_packed = 0;
}
// return the all_rects_packed status
return all_rects_packed;
}
#endif
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/tiny_ttf/stb_truetype_htcw.h | // stb_truetype.h - v1.26htcw (fork to enable streaming and low memory environments)
// stb_truetype.h - v1.26 - public domain
// authored from 2009-2021 by Sean Barrett / RAD Game Tools
//
// =======================================================================
//
// NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES
//
// This library does no range checking of the offsets found in the file,
// meaning an attacker can use it to read arbitrary memory.
//
// =======================================================================
//
// This library processes TrueType files:
// parse files
// extract glyph metrics
// extract glyph shapes
// render glyphs to one-channel bitmaps with antialiasing (box filter)
// render glyphs to one-channel SDF bitmaps (signed-distance field/function)
//
// Todo:
// non-MS cmaps
// crashproof on bad data
// hinting? (no longer patented)
// cleartype-style AA?
// optimize: use simple memory allocator for intermediates
// optimize: build edge-list directly from curves
// optimize: rasterize directly from curves?
//
// ADDITIONAL CONTRIBUTORS
//
// Mikko Mononen: compound shape support, more cmap formats
// Tor Andersson: kerning, subpixel rendering
// Dougall Johnson: OpenType / Type 2 font handling
// Daniel Ribeiro Maciel: basic GPOS-based kerning
//
// Misc other:
// Ryan Gordon
// Simon Glass
// github:IntellectualKitty
// Imanol Celaya
// Daniel Ribeiro Maciel
//
// Bug/warning reports/fixes:
// "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe
// Cass Everitt Martins Mozeiko github:aloucks
// stoiko (Haemimont Games) Cap Petschulat github:oyvindjam
// Brian Hook Omar Cornut github:vassvik
// Walter van Niftrik Ryan Griege
// David Gow Peter LaValle
// David Given Sergey Popov
// Ivan-Assen Ivanov Giumo X. Clanjor
// Anthony Pesch Higor Euripedes
// Johan Duparc Thomas Fields
// Hou Qiming Derek Vinyard
// Rob Loach Cort Stratton
// Kenney Phillis Jr. Brian Costabile
// Ken Voskuil (kaesve)
//
// VERSION HISTORY
//
// 1.26 (2021-08-28) fix broken rasterizer
// 1.25 (2021-07-11) many fixes
// 1.24 (2020-02-05) fix warning
// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS)
// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined
// 1.21 (2019-02-25) fix warning
// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()
// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod
// 1.18 (2018-01-29) add missing function
// 1.17 (2017-07-23) make more arguments const; doc fix
// 1.16 (2017-07-12) SDF support
// 1.15 (2017-03-03) make more arguments const
// 1.14 (2017-01-16) num-fonts-in-TTC function
// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
// 1.11 (2016-04-02) fix unused-variable warning
// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef
// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly
// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
// variant PackFontRanges to pack and render in separate phases;
// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
// fixed an assert() bug in the new rasterizer
// replace assert() with STBTT_assert() in new rasterizer
//
// Full history can be found at the end of this file.
//
// LICENSE
//
// See end of file for license information.
//
// USAGE
//
// Include this file in whatever places need to refer to it. In ONE C/C++
// file, write:
// #define STB_TRUETYPE_IMPLEMENTATION
// before the #include of this file. This expands out the actual
// implementation into that C/C++ file.
//
// To make the implementation private to the file that generates the implementation,
// #define STBTT_STATIC
//
// Simple 3D API (don't ship this, but it's fine for tools and quick start)
// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture
// stbtt_GetBakedQuad() -- compute quad to draw for a given char
//
// Improved 3D API (more shippable):
// #include "stb_rect_pack.h" -- optional, but you really want it
// stbtt_PackBegin()
// stbtt_PackSetOversampling() -- for improved quality on small fonts
// stbtt_PackFontRanges() -- pack and renders
// stbtt_PackEnd()
// stbtt_GetPackedQuad()
//
// "Load" a font file from a memory buffer (you have to keep the buffer loaded)
// stbtt_InitFont()
// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections
// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections
//
// Render a unicode codepoint to a bitmap
// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap
// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide
// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be
//
// Character advance/positioning
// stbtt_GetCodepointHMetrics()
// stbtt_GetFontVMetrics()
// stbtt_GetFontVMetricsOS2()
// stbtt_GetCodepointKernAdvance()
//
// Starting with version 1.06, the rasterizer was replaced with a new,
// faster and generally-more-precise rasterizer. The new rasterizer more
// accurately measures pixel coverage for anti-aliasing, except in the case
// where multiple shapes overlap, in which case it overestimates the AA pixel
// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If
// this turns out to be a problem, you can re-enable the old rasterizer with
// #define STBTT_RASTERIZER_VERSION 1
// which will incur about a 15% speed hit.
//
// ADDITIONAL DOCUMENTATION
//
// Immediately after this block comment are a series of sample programs.
//
// After the sample programs is the "header file" section. This section
// includes documentation for each API function.
//
// Some important concepts to understand to use this library:
//
// Codepoint
// Characters are defined by unicode codepoints, e.g. 65 is
// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
// the hiragana for "ma".
//
// Glyph
// A visual character shape (every codepoint is rendered as
// some glyph)
//
// Glyph index
// A font-specific integer ID representing a glyph
//
// Baseline
// Glyph shapes are defined relative to a baseline, which is the
// bottom of uppercase characters. Characters extend both above
// and below the baseline.
//
// Current Point
// As you draw text to the screen, you keep track of a "current point"
// which is the origin of each character. The current point's vertical
// position is the baseline. Even "baked fonts" use this model.
//
// Vertical Font Metrics
// The vertical qualities of the font, used to vertically position
// and space the characters. See docs for stbtt_GetFontVMetrics.
//
// Font Size in Pixels or Points
// The preferred interface for specifying font sizes in stb_truetype
// is to specify how tall the font's vertical extent should be in pixels.
// If that sounds good enough, skip the next paragraph.
//
// Most font APIs instead use "points", which are a common typographic
// measurement for describing font size, defined as 72 points per inch.
// stb_truetype provides a point API for compatibility. However, true
// "per inch" conventions don't make much sense on computer displays
// since different monitors have different number of pixels per
// inch. For example, Windows traditionally uses a convention that
// there are 96 pixels per inch, thus making 'inch' measurements have
// nothing to do with inches, and thus effectively defining a point to
// be 1.333 pixels. Additionally, the TrueType font data provides
// an explicit scale factor to scale a given font's glyphs to points,
// but the author has observed that this scale factor is often wrong
// for non-commercial fonts, thus making fonts scaled in points
// according to the TrueType spec incoherently sized in practice.
//
// DETAILED USAGE:
//
// Scale:
// Select how high you want the font to be, in points or pixels.
// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute
// a scale factor SF that will be used by all other functions.
//
// Baseline:
// You need to select a y-coordinate that is the baseline of where
// your text will appear. Call GetFontBoundingBox to get the baseline-relative
// bounding box for all characters. SF*-y0 will be the distance in pixels
// that the worst-case character could extend above the baseline, so if
// you want the top edge of characters to appear at the top of the
// screen where y=0, then you would set the baseline to SF*-y0.
//
// Current point:
// Set the current point where the first character will appear. The
// first character could extend left of the current point; this is font
// dependent. You can either choose a current point that is the leftmost
// point and hope, or add some padding, or check the bounding box or
// left-side-bearing of the first character to be displayed and set
// the current point based on that.
//
// Displaying a character:
// Compute the bounding box of the character. It will contain signed values
// relative to <current_point, baseline>. I.e. if it returns x0,y0,x1,y1,
// then the character should be displayed in the rectangle from
// <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1).
//
// Advancing for the next character:
// Call GlyphHMetrics, and compute 'current_point += SF * advance'.
//
//
// ADVANCED USAGE
//
// Quality:
//
// - Use the functions with Subpixel at the end to allow your characters
// to have subpixel positioning. Since the font is anti-aliased, not
// hinted, this is very import for quality. (This is not possible with
// baked fonts.)
//
// - Kerning is now supported, and if you're supporting subpixel rendering
// then kerning is worth using to give your text a polished look.
//
// Performance:
//
// - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
// if you don't do this, stb_truetype is forced to do the conversion on
// every call.
//
// - There are a lot of memory allocations. We should modify it to take
// a temp buffer and allocate from the temp buffer (without freeing),
// should help performance a lot.
//
// NOTES
//
// The system uses the raw data found in the .ttf file without changing it
// and without building auxiliary data structures. This is a bit inefficient
// on little-endian systems (the data is big-endian), but assuming you're
// caching the bitmaps or glyph shapes this shouldn't be a big deal.
//
// It appears to be very hard to programmatically determine what font a
// given file is in a general way. I provide an API for this, but I don't
// recommend it.
//
//
// PERFORMANCE MEASUREMENTS FOR 1.06:
//
// 32-bit 64-bit
// Previous release: 8.83 s 7.68 s
// Pool allocations: 7.72 s 6.34 s
// Inline sort : 6.54 s 5.65 s
// New rasterizer : 5.63 s 5.00 s
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
////
//// SAMPLE PROGRAMS
////
//
// Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless.
// See "tests/truetype_demo_win32.c" for a complete version.
#if 0
#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
#include "stb_truetype.h"
unsigned char ttf_buffer[1 << 20];
unsigned char temp_bitmap[512 * 512];
stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
GLuint ftex;
void my_stbtt_initfont(void)
{
fread(ttf_buffer, 1, 1 << 20, fopen("c:/windows/fonts/times.ttf", "rb"));
stbtt_BakeFontBitmap(ttf_buffer, 0, 32.0, temp_bitmap, 512, 512, 32, 96, cdata); // no guarantee this fits!
// can free ttf_buffer at this point
glGenTextures(1, &ftex);
glBindTexture(GL_TEXTURE_2D, ftex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512, 512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
// can free temp_bitmap at this point
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
void my_stbtt_print(float x, float y, char * text)
{
// assume orthographic projection with units = screen pixels, origin at top left
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ftex);
glBegin(GL_QUADS);
while(*text) {
if(*text >= 32 && *text < 128) {
stbtt_aligned_quad q;
stbtt_GetBakedQuad(cdata, 512, 512, *text - 32, &x, &y, &q, 1);//1=opengl & d3d10+,0=d3d9
glTexCoord2f(q.s0, q.t0);
glVertex2f(q.x0, q.y0);
glTexCoord2f(q.s1, q.t0);
glVertex2f(q.x1, q.y0);
glTexCoord2f(q.s1, q.t1);
glVertex2f(q.x1, q.y1);
glTexCoord2f(q.s0, q.t1);
glVertex2f(q.x0, q.y1);
}
++text;
}
glEnd();
}
#endif
//
//
//////////////////////////////////////////////////////////////////////////////
//
// Complete program (this compiles): get a single bitmap, print as ASCII art
//
#if 0
#include <stdio.h>
#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
#include "stb_truetype.h"
char ttf_buffer[1 << 25];
int main(int argc, char ** argv)
{
stbtt_fontinfo font;
unsigned char * bitmap;
int w, h, i, j, c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
fread(ttf_buffer, 1, 1 << 25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer, 0));
bitmap = stbtt_GetCodepointBitmap(&font, 0, stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0, 0);
for(j = 0; j < h; ++j) {
for(i = 0; i < w; ++i)
putchar(" .:ioVM@"[bitmap[j * w + i] >> 5]);
putchar('\n');
}
return 0;
}
#endif
//
// Output:
//
// .ii.
// @@@@@@.
// V@Mio@@o
// :i. V@V
// :oM@@M
// :@@@MM@M
// @@o o@M
// :@@. M@M
// @@@o@@@@
// :M@@V:@@.
//
//////////////////////////////////////////////////////////////////////////////
//
// Complete program: print "Hello World!" banner, with bugs
//
#if 0
char buffer[24 << 20];
unsigned char screen[20][79];
int main(int arg, char ** argv)
{
stbtt_fontinfo font;
int i, j, ascent, baseline, ch = 0;
float scale, xpos = 2; // leave a little padding in case the character extends left
char * text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness
fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
stbtt_InitFont(&font, buffer, 0);
scale = stbtt_ScaleForPixelHeight(&font, 15);
stbtt_GetFontVMetrics(&font, &ascent, 0, 0);
baseline = (int)(ascent * scale);
while(text[ch]) {
int advance, lsb, x0, y0, x1, y1;
float x_shift = xpos - (float)floor(xpos);
stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale, scale, x_shift, 0, &x0, &y0, &x1, &y1);
stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int)xpos + x0], x1 - x0, y1 - y0, 79, scale, scale,
x_shift, 0, text[ch]);
// note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
// because this API is really for baking character bitmaps into textures. if you want to render
// a sequence of characters, you really need to render each bitmap to a temp buffer, then
// "alpha blend" that into the working buffer
xpos += (advance * scale);
if(text[ch + 1])
xpos += scale * stbtt_GetCodepointKernAdvance(&font, text[ch], text[ch + 1]);
++ch;
}
for(j = 0; j < 20; ++j) {
for(i = 0; i < 78; ++i)
putchar(" .:ioVM@"[screen[j][i] >> 5]);
putchar('\n');
}
return 0;
}
#endif
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
////
//// INTEGRATION WITH YOUR CODEBASE
////
//// The following sections allow you to supply alternate definitions
//// of C library functions used by stb_truetype, e.g. if you don't
//// link with the C runtime library.
#ifdef STB_TRUETYPE_IMPLEMENTATION
// #define your own (u)stbtt_int8/16/32 before including to override this
#ifndef stbtt_uint8
typedef unsigned char stbtt_uint8;
typedef signed char stbtt_int8;
typedef unsigned short stbtt_uint16;
typedef signed short stbtt_int16;
typedef unsigned int stbtt_uint32;
typedef signed int stbtt_int32;
#endif
typedef char stbtt__check_size32[sizeof(stbtt_int32) == 4 ? 1 : -1];
typedef char stbtt__check_size16[sizeof(stbtt_int16) == 2 ? 1 : -1];
// define STBTT_STDIO_STREAM to stream from a FILE object
// instead of from memory. Or define STBTT_STREAM_TYPE,
// STBTT_STREAM_READ and STBTT_STREAM_SEEK to implement
// another streaming source
#ifdef STBTT_STDIO_STREAM
#include <stdio.h>
#define STBTT_STREAM_TYPE FILE*
#define STBTT_STREAM_READ(s,x,y) fread(x,1,y,s);
#define STBTT_STREAM_SEEK(s,x) fseek(s,x,SEEK_SET);
#endif
// heap factor sizes for various counts of objects
// adjust for your platform. Below is suitable for
// modern PC class machines.
#ifndef STBTT_HEAP_FACTOR_SIZE_32
#define STBTT_HEAP_FACTOR_SIZE_32 2000
#endif
#ifndef STBTT_HEAP_FACTOR_SIZE_128
#define STBTT_HEAP_FACTOR_SIZE_128 800
#endif
#ifndef STBTT_HEAP_FACTOR_SIZE_DEFAULT
#define STBTT_HEAP_FACTOR_SIZE_DEFAULT 100
#endif
// e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
#ifndef STBTT_ifloor
#include <math.h>
#define STBTT_ifloor(x) ((int) floor(x))
#define STBTT_iceil(x) ((int) ceil(x))
#endif
#ifndef STBTT_sqrt
#include <math.h>
#define STBTT_sqrt(x) (float)sqrt(x)
#define STBTT_pow(x,y) pow(x,y)
#endif
#ifndef STBTT_fmod
#include <math.h>
#define STBTT_fmod(x,y) fmod(x,y)
#endif
#ifndef STBTT_cos
#include <math.h>
#define STBTT_cos(x) cos(x)
#define STBTT_acos(x) acos(x)
#endif
#ifndef STBTT_fabs
#include <math.h>
#define STBTT_fabs(x) (float)fabs(x)
#endif
// #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
#ifndef STBTT_malloc
#include <stdlib.h>
#define STBTT_malloc(x,u) ((void)(u),malloc(x))
#define STBTT_free(x,u) ((void)(u),free(x))
#endif
#ifndef STBTT_assert
#include <assert.h>
#define STBTT_assert(x) assert(x)
#endif
#ifndef STBTT_strlen
#include <string.h>
#define STBTT_strlen(x) strlen(x)
#endif
#ifndef STBTT_memcpy
#include <string.h>
#define STBTT_memcpy memcpy
#define STBTT_memset memset
#endif
#endif
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
////
//// INTERFACE
////
////
#ifndef __STB_INCLUDE_STB_TRUETYPE_H__
#define __STB_INCLUDE_STB_TRUETYPE_H__
#ifdef STBTT_STATIC
#define STBTT_DEF static
#else
#define STBTT_DEF extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
// private structure
typedef struct {
#ifdef STBTT_STREAM_TYPE
STBTT_STREAM_TYPE data;
stbtt_uint32 offset;
#else
unsigned char * data;
#endif
int cursor;
int size;
} stbtt__buf;
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function"
#endif
//////////////////////////////////////////////////////////////////////////////
//
// TEXTURE BAKING API
//
// If you use this API, you only have to call two functions ever.
//
typedef struct {
unsigned short x0, y0, x1, y1; // coordinates of bbox in bitmap
float xoff, yoff, xadvance;
} stbtt_bakedchar;
typedef struct {
float x0, y0, s0, t0; // top-left
float x1, y1, s1, t1; // bottom-right
} stbtt_aligned_quad;
STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar * chardata, int pw, int ph, // same data as above
int char_index, // character to display
float * xpos, float * ypos, // pointers to current position in screen pixel space
stbtt_aligned_quad * q, // output: quad to draw
int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier
// Call GetBakedQuad with char_index = 'character - first_char', and it
// creates the quad you need to draw and advances the current position.
//
// The coordinate system used assumes y increases downwards.
//
// Characters will extend both above and below the current position;
// see discussion of "BASELINE" above.
//
// It's inefficient; you might want to c&p it and optimize it.
//////////////////////////////////////////////////////////////////////////////
//
// NEW TEXTURE BAKING API
//
// This provides options for packing multiple fonts into one atlas, not
// perfectly but better than nothing.
typedef struct {
unsigned short x0, y0, x1, y1; // coordinates of bbox in bitmap
float xoff, yoff, xadvance;
float xoff2, yoff2;
} stbtt_packedchar;
/// @cond
/**
* Tells Doxygen to ignore a duplicate declaration
*/
typedef struct stbtt_pack_context stbtt_pack_context;
typedef struct stbtt_fontinfo stbtt_fontinfo;
/// @endcond
#ifndef STB_RECT_PACK_VERSION
/// @cond
/**
* Tells Doxygen to ignore a duplicate declaration
*/
typedef struct stbrp_rect stbrp_rect;
/// @endcond
#endif
STBTT_DEF int stbtt_PackBegin(stbtt_pack_context * spc, unsigned char * pixels, int width, int height,
int stride_in_bytes, int padding, void * alloc_context);
// Initializes a packing context stored in the passed-in stbtt_pack_context.
// Future calls using this context will pack characters into the bitmap passed
// in here: a 1-channel bitmap that is width * height. stride_in_bytes is
// the distance from one row to the next (or 0 to mean they are packed tightly
// together). "padding" is the amount of padding to leave between each
// character (normally you want '1' for bitmaps you'll use as textures with
// bilinear filtering).
//
// Returns 0 on failure, 1 on success.
STBTT_DEF void stbtt_PackEnd(stbtt_pack_context * spc);
// Cleans up the packing context and frees all memory.
#define STBTT_POINT_SIZE(x) (-(x))
typedef struct {
float font_size;
int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint
int * array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints
int num_chars;
stbtt_packedchar * chardata_for_range; // output
unsigned char h_oversample, v_oversample; // don't set these, they're used internally
} stbtt_pack_range;
STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context * spc, unsigned int h_oversample,
unsigned int v_oversample);
// Oversampling a font increases the quality by allowing higher-quality subpixel
// positioning, and is especially valuable at smaller text sizes.
//
// This function sets the amount of oversampling for all following calls to
// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given
// pack context. The default (no oversampling) is achieved by h_oversample=1
// and v_oversample=1. The total number of pixels required is
// h_oversample*v_oversample larger than the default; for example, 2x2
// oversampling requires 4x the storage of 1x1. For best results, render
// oversampled textures with bilinear filtering. Look at the readme in
// stb/tests/oversample for information about oversampled fonts
//
// To use with PackFontRangesGather etc., you must set it before calls
// call to PackFontRangesGatherRects.
STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context * spc, int skip);
// If skip != 0, this tells stb_truetype to skip any codepoints for which
// there is no corresponding glyph. If skip=0, which is the default, then
// codepoints without a glyph received the font's "missing character" glyph,
// typically an empty box by convention.
STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar * chardata, int pw, int ph, // same data as above
int char_index, // character to display
float * xpos, float * ypos, // pointers to current position in screen pixel space
stbtt_aligned_quad * q, // output: quad to draw
int align_to_integer);
STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context * spc, const stbtt_fontinfo * info,
stbtt_pack_range * ranges, int num_ranges, stbrp_rect * rects);
STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context * spc, stbrp_rect * rects, int num_rects);
STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context * spc, const stbtt_fontinfo * info,
stbtt_pack_range * ranges, int num_ranges, stbrp_rect * rects);
// Calling these functions in sequence is roughly equivalent to calling
// stbtt_PackFontRanges(). If you more control over the packing of multiple
// fonts, or if you want to pack custom data into a font texture, take a look
// at the source to of stbtt_PackFontRanges() and create a custom version
// using these functions, e.g. call GatherRects multiple times,
// building up a single array of rects, then call PackRects once,
// then call RenderIntoRects repeatedly. This may result in a
// better packing than calling PackFontRanges multiple times
// (or it may not).
// this is an opaque structure that you shouldn't mess with which holds
// all the context needed from PackBegin to PackEnd.
struct stbtt_pack_context {
void * user_allocator_context;
void * pack_info;
int width;
int height;
int stride_in_bytes;
int padding;
int skip_missing;
unsigned int h_oversample, v_oversample;
unsigned char * pixels;
void * nodes;
};
//////////////////////////////////////////////////////////////////////////////
//
// FONT LOADING
//
//
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_GetNumberOfFonts(STBTT_STREAM_TYPE data);
#else
STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char * data);
#endif
// This function will determine the number of fonts in a font file. TrueType
// collection (.ttc) files may contain multiple fonts, while TrueType font
// (.ttf) files only contain one font. The number of fonts can be used for
// indexing with the previous function where the index is between zero and one
// less than the total fonts. If an error occurs, -1 is returned.
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_GetFontOffsetForIndex(STBTT_STREAM_TYPE, int index);
#else
STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char * data, int index);
#endif
// Each .ttf/.ttc file may have more than one font. Each font has a sequential
// index number starting from 0. Call this function to get the font offset for
// a given index; it returns -1 if the index is out of range. A regular .ttf
// file will only define one font and it always be at offset 0, so it will
// return '0' for index 0, and -1 for all other indices.
// The following structure is defined publicly so you can declare one on
// the stack or as a global or etc, but you should treat it as opaque.
struct stbtt_fontinfo {
void * userdata;
#ifdef STBTT_STREAM_TYPE
STBTT_STREAM_TYPE data;
#else
unsigned char * data; // pointer to .ttf file
#endif
int fontstart; // offset of start of font
int numGlyphs; // number of glyphs, needed for range checking
int loca, head, glyf, hhea, hmtx, kern, gpos, svg; // table locations as offset from start of .ttf
int index_map; // a cmap mapping for our chosen character encoding
int indexToLocFormat; // format needed to map from glyph index to glyph
stbtt__buf cff; // cff font data
stbtt__buf charstrings; // the charstring index
stbtt__buf gsubrs; // global charstring subroutines index
stbtt__buf subrs; // private charstring subroutines index
stbtt__buf fontdicts; // array of font dicts
stbtt__buf fdselect; // map from glyph to fontdict
};
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_InitFont(stbtt_fontinfo * info, STBTT_STREAM_TYPE data, int offset);
#else
STBTT_DEF int stbtt_InitFont(stbtt_fontinfo * info, const unsigned char * data, int offset);
#endif
// Given an offset into the file that defines a font, this function builds
// the necessary cached info for the rest of the system. You must allocate
// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
// need to do anything special to free it, because the contents are pure
// value data with no additional data structures. Returns 0 on failure.
//////////////////////////////////////////////////////////////////////////////
//
// CHARACTER TO GLYPH-INDEX CONVERSIOn
STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo * info, int unicode_codepoint);
// If you're going to perform multiple operations on the same character
// and you want a speed-up, call this function with the character you're
// going to process, then use glyph-based functions instead of the
// codepoint-based functions.
// Returns 0 if the character codepoint is not defined in the font.
//////////////////////////////////////////////////////////////////////////////
//
// CHARACTER PROPERTIES
//
STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo * info, float pixels);
// computes a scale factor to produce a font whose "height" is 'pixels' tall.
// Height is measured as the distance from the highest ascender to the lowest
// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
// and computing:
// scale = pixels / (ascent - descent)
// so if you prefer to measure height by the ascent only, use a similar calculation.
STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo * info, float pixels);
// computes a scale factor to produce a font whose EM size is mapped to
// 'pixels' tall. This is probably what traditional APIs compute, but
// I'm not positive.
STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo * info, int * ascent, int * descent, int * lineGap);
// ascent is the coordinate above the baseline the font extends; descent
// is the coordinate below the baseline the font extends (i.e. it is typically negative)
// lineGap is the spacing between one row's descent and the next row's ascent...
// so you should advance the vertical position by "*ascent - *descent + *lineGap"
// these are expressed in unscaled coordinates, so you must multiply by
// the scale factor for a given size
STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo * info, int * typoAscent, int * typoDescent,
int * typoLineGap);
// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2
// table (specific to MS/Windows TTF files).
//
// Returns 1 on success (table present), 0 on failure.
STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo * info, int * x0, int * y0, int * x1, int * y1);
// the bounding box around all possible characters
STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo * info, int codepoint, int * advanceWidth,
int * leftSideBearing);
// leftSideBearing is the offset from the current horizontal position to the left edge of the character
// advanceWidth is the offset from the current horizontal position to the next horizontal position
// these are expressed in unscaled coordinates
STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo * info, int ch1, int ch2);
// an additional amount to add to the 'advance' value between ch1 and ch2
STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo * info, int codepoint, int * x0, int * y0, int * x1, int * y1);
// Gets the bounding box of the visible part of the glyph, in unscaled coordinates
STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo * info, int glyph_index, int * advanceWidth,
int * leftSideBearing);
STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo * info, int glyph1, int glyph2);
STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo * info, int glyph_index, int * x0, int * y0, int * x1, int * y1);
// as above, but takes one or more glyph indices for greater efficiency
typedef struct _stbtt_kerningentry {
int glyph1; // use stbtt_FindGlyphIndex
int glyph2;
int advance;
} stbtt_kerningentry;
STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo * info);
STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo * info, stbtt_kerningentry * table, int table_length);
// Retrieves a complete list of all of the kerning pairs provided by the font
// stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write.
// The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1)
//////////////////////////////////////////////////////////////////////////////
//
// GLYPH SHAPES (you probably don't need these, but they have to go before
// the bitmaps for C declaration-order reasons)
//
#ifndef STBTT_vmove // you can predefine these to use different values (but why?)
enum {
STBTT_vmove = 1,
STBTT_vline,
STBTT_vcurve,
STBTT_vcubic
};
#endif
#ifndef stbtt_vertex // you can predefine this to use different values
// (we share this with other code at RAD)
#define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
typedef struct {
stbtt_vertex_type x, y, cx, cy, cx1, cy1;
unsigned char type, padding;
} stbtt_vertex;
#endif
STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo * info, int glyph_index);
// returns non-zero if nothing is drawn for this glyph
STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo * info, int unicode_codepoint, stbtt_vertex ** vertices);
STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo * info, int glyph_index, stbtt_vertex ** vertices);
// returns # of vertices and fills *vertices with the pointer to them
// these are expressed in "unscaled" coordinates
//
// The shape is a series of contours. Each one starts with
// a STBTT_moveto, then consists of a series of mixed
// STBTT_lineto and STBTT_curveto segments. A lineto
// draws a line from previous endpoint to its x,y; a curveto
// draws a quadratic bezier from previous endpoint to
// its x,y, using cx,cy as the bezier control point.
STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo * info, stbtt_vertex * vertices);
// frees the data allocated above
STBTT_DEF stbtt_uint32 stbtt_FindSVGDoc(const stbtt_fontinfo * info, int gl);
STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo * info, int unicode_codepoint, stbtt_uint32 * svgOfs);
STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo * info, int gl, stbtt_uint32 * svgOfs);
// fills svg with the character's SVG data.
// returns data size or 0 if SVG not found.
//////////////////////////////////////////////////////////////////////////////
//
// BITMAP RENDERING
//
STBTT_DEF void stbtt_FreeBitmap(unsigned char * bitmap, void * userdata);
// frees the bitmap allocated below
STBTT_DEF unsigned char * stbtt_GetCodepointBitmap(const stbtt_fontinfo * info, float scale_x, float scale_y,
int codepoint, int * width, int * height, int * xoff, int * yoff);
// allocates a large-enough single-channel 8bpp bitmap and renders the
// specified character/glyph at the specified scale into it, with
// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
// *width & *height are filled out with the width & height of the bitmap,
// which is stored left-to-right, top-to-bottom.
//
// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
STBTT_DEF unsigned char * stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo * info, float scale_x, float scale_y,
float shift_x, float shift_y, int codepoint, int * width, int * height, int * xoff, int * yoff);
// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
// shift for the character
STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo * info, unsigned char * output, int out_w, int out_h,
int out_stride, float scale_x, float scale_y, int codepoint);
// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
// width and height and positioning info for it first.
STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo * info, unsigned char * output, int out_w,
int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint);
// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
// shift for the character
STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo * info, unsigned char * output,
int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x,
int oversample_y, float * sub_x, float * sub_y, int codepoint);
// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering
// is performed (see stbtt_PackSetOversampling)
STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo * font, int codepoint, float scale_x, float scale_y,
int * ix0, int * iy0, int * ix1, int * iy1);
// get the bbox of the bitmap centered around the glyph origin; so the
// bitmap width is ix1-ix0, height is iy1-iy0, and location to place
// the bitmap top left is (leftSideBearing*scale,iy0).
// (Note that the bitmap uses y-increases-down, but the shape uses
// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo * font, int codepoint, float scale_x,
float scale_y, float shift_x, float shift_y, int * ix0, int * iy0, int * ix1, int * iy1);
// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
// shift for the character
// the following functions are equivalent to the above functions, but operate
// on glyph indices instead of Unicode codepoints (for efficiency)
STBTT_DEF unsigned char * stbtt_GetGlyphBitmap(const stbtt_fontinfo * info, float scale_x, float scale_y, int glyph,
int * width, int * height, int * xoff, int * yoff);
STBTT_DEF unsigned char * stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo * info, float scale_x, float scale_y,
float shift_x, float shift_y, int glyph, int * width, int * height, int * xoff, int * yoff);
STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo * info, unsigned char * output, int out_w, int out_h,
int out_stride, float scale_x, float scale_y, int glyph);
STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo * info, unsigned char * output, int out_w, int out_h,
int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph);
STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo * info, unsigned char * output, int out_w,
int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x,
int oversample_y, float * sub_x, float * sub_y, int glyph);
STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo * font, int glyph, float scale_x, float scale_y, int * ix0,
int * iy0, int * ix1, int * iy1);
STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo * font, int glyph, float scale_x, float scale_y,
float shift_x, float shift_y, int * ix0, int * iy0, int * ix1, int * iy1);
// @TODO: don't expose this structure
typedef struct {
int w, h, stride;
unsigned char * pixels;
} stbtt__bitmap;
// rasterize a shape with quadratic beziers into a bitmap
STBTT_DEF void stbtt_Rasterize(stbtt__bitmap * result, // 1-channel bitmap to draw into
float flatness_in_pixels, // allowable error of curve in pixels
stbtt_vertex * vertices, // array of vertices defining shape
int num_verts, // number of vertices in above array
float scale_x, float scale_y, // scale applied to input vertices
float shift_x, float shift_y, // translation applied to input vertices
int x_off, int y_off, // another translation applied to input
int invert, // if non-zero, vertically flip shape
void * userdata); // context for to STBTT_MALLOC
//////////////////////////////////////////////////////////////////////////////
//
// Signed Distance Function (or Field) rendering
STBTT_DEF void stbtt_FreeSDF(unsigned char * bitmap, void * userdata);
// frees the SDF bitmap allocated below
STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo * info, float scale, int glyph, int padding,
unsigned char onedge_value, float pixel_dist_scale, int * width, int * height, int * xoff, int * yoff);
STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo * info, float scale, int codepoint, int padding,
unsigned char onedge_value, float pixel_dist_scale, int * width, int * height, int * xoff, int * yoff);
// These functions compute a discretized SDF field for a single character, suitable for storing
// in a single-channel texture, sampling with bilinear filtering, and testing against
// larger than some threshold to produce scalable fonts.
// info -- the font
// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap
// glyph/codepoint -- the character to generate the SDF for
// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0),
// which allows effects like bit outlines
// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character)
// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale)
// if positive, > onedge_value is inside; if negative, < onedge_value is inside
// width,height -- output height & width of the SDF bitmap (including padding)
// xoff,yoff -- output origin of the character
// return value -- a 2D array of bytes 0..255, width*height in size
//
// pixel_dist_scale & onedge_value are a scale & bias that allows you to make
// optimal use of the limited 0..255 for your application, trading off precision
// and special effects. SDF values outside the range 0..255 are clamped to 0..255.
//
// Example:
// scale = stbtt_ScaleForPixelHeight(22)
// padding = 5
// onedge_value = 180
// pixel_dist_scale = 180/5.0 = 36.0
//
// This will create an SDF bitmap in which the character is about 22 pixels
// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled
// shape, sample the SDF at each pixel and fill the pixel if the SDF value
// is greater than or equal to 180/255. (You'll actually want to antialias,
// which is beyond the scope of this example.) Additionally, you can compute
// offset outlines (e.g. to stroke the character border inside & outside,
// or only outside). For example, to fill outside the character up to 3 SDF
// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above
// choice of variables maps a range from 5 pixels outside the shape to
// 2 pixels inside the shape to 0..255; this is intended primarily for apply
// outside effects only (the interior range is needed to allow proper
// antialiasing of the font at *smaller* sizes)
//
// The function computes the SDF analytically at each SDF pixel, not by e.g.
// building a higher-res bitmap and approximating it. In theory the quality
// should be as high as possible for an SDF of this size & representation, but
// unclear if this is true in practice (perhaps building a higher-res bitmap
// and computing from that can allow drop-out prevention).
//
// The algorithm has not been optimized at all, so expect it to be slow
// if computing lots of characters or very large sizes.
//////////////////////////////////////////////////////////////////////////////
//
// Finding the right font...
//
// You should really just solve this offline, keep your own tables
// of what font is what, and don't try to get it out of the .ttf file.
// That's because getting it out of the .ttf file is really hard, because
// the names in the file can appear in many possible encodings, in many
// possible languages, and e.g. if you need a case-insensitive comparison,
// the details of that depend on the encoding & language in a complex way
// (actually underspecified in truetype, but also gigantic).
//
// But you can use the provided functions in two possible ways:
// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
// unicode-encoded names to try to find the font you want;
// you can run this before calling stbtt_InitFont()
//
// stbtt_GetFontNameString() lets you get any of the various strings
// from the file yourself and do your own comparisons on them.
// You have to have called stbtt_InitFont() first.
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_FindMatchingFont(STBTT_STREAM_TYPE fontdata, const char * name, int flags);
#else
STBTT_DEF int stbtt_FindMatchingFont(const unsigned char * fontdata, const char * name, int flags);
#endif
// returns the offset (not index) of the font that matches, or -1 if none
// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
// if you use any other flag, use a font name like "Arial"; this checks
// the 'macStyle' header field; i don't know if fonts set this consistently
#define STBTT_MACSTYLE_DONTCARE 0
#define STBTT_MACSTYLE_BOLD 1
#define STBTT_MACSTYLE_ITALIC 2
#define STBTT_MACSTYLE_UNDERSCORE 4
#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char * s1, int len1, STBTT_STREAM_TYPE s2, stbtt_uint32 s2offs,
int len2);
#else
STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char * s1, int len1, const char * s2, stbtt_uint32 s2offs,
int len2);
#endif
// returns 1/0 whether the first string interpreted as utf8 is identical to
// the second string interpreted as big-endian utf16... useful for strings from next func
STBTT_DEF stbtt_uint32 stbtt_GetFontNameString(const stbtt_fontinfo * font, int * length, int platformID,
int encodingID, int languageID, int nameID);
// returns the string (which may be big-endian double byte, e.g. for unicode)
// and puts the length in bytes in *length.
//
// some of the values for the IDs are below; for more see the truetype spec:
// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
// http://www.microsoft.com/typography/otspec/name.htm
enum { // platformID
STBTT_PLATFORM_ID_UNICODE = 0,
STBTT_PLATFORM_ID_MAC = 1,
STBTT_PLATFORM_ID_ISO = 2,
STBTT_PLATFORM_ID_MICROSOFT = 3
};
enum { // encodingID for STBTT_PLATFORM_ID_UNICODE
STBTT_UNICODE_EID_UNICODE_1_0 = 0,
STBTT_UNICODE_EID_UNICODE_1_1 = 1,
STBTT_UNICODE_EID_ISO_10646 = 2,
STBTT_UNICODE_EID_UNICODE_2_0_BMP = 3,
STBTT_UNICODE_EID_UNICODE_2_0_FULL = 4
};
enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT
STBTT_MS_EID_SYMBOL = 0,
STBTT_MS_EID_UNICODE_BMP = 1,
STBTT_MS_EID_SHIFTJIS = 2,
STBTT_MS_EID_UNICODE_FULL = 10
};
enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
STBTT_MAC_EID_ROMAN = 0, STBTT_MAC_EID_ARABIC = 4,
STBTT_MAC_EID_JAPANESE = 1, STBTT_MAC_EID_HEBREW = 5,
STBTT_MAC_EID_CHINESE_TRAD = 2, STBTT_MAC_EID_GREEK = 6,
STBTT_MAC_EID_KOREAN = 3, STBTT_MAC_EID_RUSSIAN = 7
};
enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
// problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
STBTT_MS_LANG_ENGLISH = 0x0409, STBTT_MS_LANG_ITALIAN = 0x0410,
STBTT_MS_LANG_CHINESE = 0x0804, STBTT_MS_LANG_JAPANESE = 0x0411,
STBTT_MS_LANG_DUTCH = 0x0413, STBTT_MS_LANG_KOREAN = 0x0412,
STBTT_MS_LANG_FRENCH = 0x040c, STBTT_MS_LANG_RUSSIAN = 0x0419,
STBTT_MS_LANG_GERMAN = 0x0407, STBTT_MS_LANG_SPANISH = 0x0409,
STBTT_MS_LANG_HEBREW = 0x040d, STBTT_MS_LANG_SWEDISH = 0x041D
};
enum { // languageID for STBTT_PLATFORM_ID_MAC
STBTT_MAC_LANG_ENGLISH = 0, STBTT_MAC_LANG_JAPANESE = 11,
STBTT_MAC_LANG_ARABIC = 12, STBTT_MAC_LANG_KOREAN = 23,
STBTT_MAC_LANG_DUTCH = 4, STBTT_MAC_LANG_RUSSIAN = 32,
STBTT_MAC_LANG_FRENCH = 1, STBTT_MAC_LANG_SPANISH = 6,
STBTT_MAC_LANG_GERMAN = 2, STBTT_MAC_LANG_SWEDISH = 5,
STBTT_MAC_LANG_HEBREW = 10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED = 33,
STBTT_MAC_LANG_ITALIAN = 3, STBTT_MAC_LANG_CHINESE_TRAD = 19
};
#ifdef __cplusplus
}
#endif
#endif // __STB_INCLUDE_STB_TRUETYPE_H__
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
////
//// IMPLEMENTATION
////
////
#ifdef STB_TRUETYPE_IMPLEMENTATION
#ifndef STBTT_MAX_OVERSAMPLE
#define STBTT_MAX_OVERSAMPLE 8
#endif
#if STBTT_MAX_OVERSAMPLE > 255
#error "STBTT_MAX_OVERSAMPLE cannot be > 255"
#endif
typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE - 1)) == 0 ? 1 : -1];
#ifndef STBTT_RASTERIZER_VERSION
#define STBTT_RASTERIZER_VERSION 2
#endif
#ifdef _MSC_VER
#define STBTT__NOTUSED(v) (void)(v)
#else
#define STBTT__NOTUSED(v) (void)sizeof(v)
#endif
//////////////////////////////////////////////////////////////////////////
//
// stbtt__buf helpers to parse data from file
//
static stbtt_uint8 stbtt__buf_get8(stbtt__buf * b)
{
if(b->cursor >= b->size)
return 0;
#ifdef STBTT_STREAM_TYPE
long pos = (long)(b->cursor + b->offset);
STBTT_STREAM_SEEK(b->data, pos);
stbtt_uint8 result;
STBTT_STREAM_READ(b->data, &result, 1);
++b->cursor;
return result;
#else
return b->data[b->cursor++];
#endif
}
static stbtt_uint8 stbtt__buf_peek8(stbtt__buf * b)
{
if(b->cursor >= b->size)
return 0;
#ifdef STBTT_STREAM_TYPE
long pos = (long)(b->cursor + b->offset);
STBTT_STREAM_SEEK(b->data, pos);
stbtt_uint8 result;
STBTT_STREAM_READ(b->data, &result, 1);
return result;
#else
return b->data[b->cursor];
#endif
}
static void stbtt__buf_seek(stbtt__buf * b, int o)
{
STBTT_assert(!(o > b->size || o < 0));
b->cursor = (o > b->size || o < 0) ? b->size : o;
}
static void stbtt__buf_skip(stbtt__buf * b, int o)
{
stbtt__buf_seek(b, b->cursor + o);
}
static stbtt_uint32 stbtt__buf_get(stbtt__buf * b, int n)
{
stbtt_uint32 v = 0;
int i;
STBTT_assert(n >= 1 && n <= 4);
for(i = 0; i < n; i++)
v = (v << 8) | stbtt__buf_get8(b);
return v;
}
#ifdef STBTT_STREAM_TYPE
static stbtt__buf stbtt__new_buf(STBTT_STREAM_TYPE s, size_t size)
#else
static stbtt__buf stbtt__new_buf(const void * p, size_t size)
#endif
{
stbtt__buf r;
STBTT_assert(size < 0x40000000);
#ifdef STBTT_STREAM_TYPE
r.data = s;
r.offset = 0;
#else
r.data = (stbtt_uint8 *)p;
#endif
r.size = (int)size;
r.cursor = 0;
return r;
}
#define stbtt__buf_get16(b) stbtt__buf_get((b), 2)
#define stbtt__buf_get32(b) stbtt__buf_get((b), 4)
static stbtt__buf stbtt__buf_range(const stbtt__buf * b, int o, int s)
{
stbtt__buf r = stbtt__new_buf(NULL, 0);
if(o < 0 || s < 0 || o > b->size || s > b->size - o) return r;
#ifdef STBTT_STREAM_TYPE
r.data = b->data;
r.offset = b->offset + o;
#else
r.data = b->data + o;
#endif
r.size = s;
return r;
}
static stbtt__buf stbtt__cff_get_index(stbtt__buf * b)
{
int count, start, offsize;
start = b->cursor;
count = stbtt__buf_get16(b);
if(count) {
offsize = stbtt__buf_get8(b);
STBTT_assert(offsize >= 1 && offsize <= 4);
stbtt__buf_skip(b, offsize * count);
stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1);
}
return stbtt__buf_range(b, start, b->cursor - start);
}
static stbtt_uint32 stbtt__cff_int(stbtt__buf * b)
{
int b0 = stbtt__buf_get8(b);
if(b0 >= 32 && b0 <= 246) return b0 - 139;
else if(b0 >= 247 && b0 <= 250) return (b0 - 247) * 256 + stbtt__buf_get8(b) + 108;
else if(b0 >= 251 && b0 <= 254) return -(b0 - 251) * 256 - stbtt__buf_get8(b) - 108;
else if(b0 == 28) return stbtt__buf_get16(b);
else if(b0 == 29) return stbtt__buf_get32(b);
STBTT_assert(0);
return 0;
}
static void stbtt__cff_skip_operand(stbtt__buf * b)
{
int v, b0 = stbtt__buf_peek8(b);
STBTT_assert(b0 >= 28);
if(b0 == 30) {
stbtt__buf_skip(b, 1);
while(b->cursor < b->size) {
v = stbtt__buf_get8(b);
if((v & 0xF) == 0xF || (v >> 4) == 0xF)
break;
}
}
else {
stbtt__cff_int(b);
}
}
static stbtt__buf stbtt__dict_get(stbtt__buf * b, int key)
{
stbtt__buf_seek(b, 0);
while(b->cursor < b->size) {
int start = b->cursor, end, op;
while(stbtt__buf_peek8(b) >= 28)
stbtt__cff_skip_operand(b);
end = b->cursor;
op = stbtt__buf_get8(b);
if(op == 12) op = stbtt__buf_get8(b) | 0x100;
if(op == key) return stbtt__buf_range(b, start, end - start);
}
return stbtt__buf_range(b, 0, 0);
}
static void stbtt__dict_get_ints(stbtt__buf * b, int key, int outcount, stbtt_uint32 * out)
{
int i;
stbtt__buf operands = stbtt__dict_get(b, key);
for(i = 0; i < outcount && operands.cursor < operands.size; i++)
out[i] = stbtt__cff_int(&operands);
}
static int stbtt__cff_index_count(stbtt__buf * b)
{
stbtt__buf_seek(b, 0);
return stbtt__buf_get16(b);
}
static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i)
{
int count, offsize, start, end;
stbtt__buf_seek(&b, 0);
count = stbtt__buf_get16(&b);
offsize = stbtt__buf_get8(&b);
STBTT_assert(i >= 0 && i < count);
STBTT_assert(offsize >= 1 && offsize <= 4);
stbtt__buf_skip(&b, i * offsize);
start = stbtt__buf_get(&b, offsize);
end = stbtt__buf_get(&b, offsize);
return stbtt__buf_range(&b, 2 + (count + 1) * offsize + start, end - start);
}
//////////////////////////////////////////////////////////////////////////
//
// accessors to parse data from file
//
// on platforms that don't allow misaligned reads, if we want to allow
// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
#ifdef STBTT_STREAM_TYPE
static stbtt_uint8 ttBYTE(STBTT_STREAM_TYPE s, stbtt_uint32 offset)
{
STBTT_STREAM_SEEK(s, offset);
stbtt_uint8 r;
STBTT_STREAM_READ(s, &r, 1);
return r;
}
#define ttCHAR(s, offset) ((stbtt_int8)ttBYTE(s,offset))
static stbtt_uint16 ttUSHORT(STBTT_STREAM_TYPE s, stbtt_uint32 offset)
{
STBTT_STREAM_SEEK(s, offset);
stbtt_uint8 r[2];
STBTT_STREAM_READ(s, &r, 2);
return r[0] * 256 + r[1];
}
static stbtt_int16 ttSHORT(STBTT_STREAM_TYPE s, stbtt_uint32 offset)
{
STBTT_STREAM_SEEK(s, offset);
stbtt_uint8 r[2];
STBTT_STREAM_READ(s, &r, 2);
return r[0] * 256 + r[1];
}
static stbtt_uint32 ttULONG(STBTT_STREAM_TYPE s, stbtt_uint32 offset)
{
STBTT_STREAM_SEEK(s, offset);
stbtt_uint8 r[4];
STBTT_STREAM_READ(s, &r, 4);
return (r[0] << 24) + (r[1] << 16) + (r[2] << 8) + r[3];
}
static stbtt_int32 ttLONG(STBTT_STREAM_TYPE s, stbtt_uint32 offset)
{
STBTT_STREAM_SEEK(s, offset);
stbtt_uint8 r[4];
STBTT_STREAM_READ(s, &r, 4);
return (r[0] << 24) + (r[1] << 16) + (r[2] << 8) + r[3];
}
#else
#define ttBYTE(p, offset) (* (stbtt_uint8 *) (p+offset))
#define ttCHAR(p, offset) (* (stbtt_int8 *) (p+offset))
static stbtt_uint16 ttUSHORT(const stbtt_uint8 * p, stbtt_uint32 offset)
{
return p[offset + 0] * 256 + p[offset + 1];
}
static stbtt_int16 ttSHORT(const stbtt_uint8 * p, stbtt_uint32 offset)
{
return p[offset + 0] * 256 + p[offset + 1];
}
static stbtt_uint32 ttULONG(const stbtt_uint8 * p, stbtt_uint32 offset)
{
return (p[offset + 0] << 24) + (p[offset + 1] << 16) + (p[offset + 2] << 8) + p[offset + 3];
}
static stbtt_int32 ttLONG(const stbtt_uint8 * p, stbtt_uint32 offset)
{
return (p[offset + 0] << 24) + (p[offset + 1] << 16) + (p[offset + 2] << 8) + p[offset + 3];
}
#endif
#define ttFixed(p, offset) ttLONG(p, offset)
#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3])
#ifdef STBTT_STREAM_TYPE
static int stbtt__isfont(STBTT_STREAM_TYPE stream, stbtt_uint32 offs)
#else
static int stbtt__isfont(stbtt_uint8 * font, stbtt_uint32 offs)
#endif
{
#ifdef STBTT_STREAM_TYPE
stbtt_uint8 font[4];
STBTT_STREAM_SEEK(stream, offs);
STBTT_STREAM_READ(stream, font, 4);
#else
font += offs;
#endif
// check the version number
if(stbtt_tag4(font, '1', 0, 0, 0)) return 1; // TrueType 1
if(stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this!
if(stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF
if(stbtt_tag4(font, 0, 1, 0, 0)) return 1; // OpenType 1.0
if(stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts
return 0;
}
// @OPTIMIZE: binary search
#ifdef STBTT_STREAM_TYPE
static stbtt_uint32 stbtt__find_table(STBTT_STREAM_TYPE data, stbtt_uint32 fontstart, const char * tag)
#else
static stbtt_uint32 stbtt__find_table(stbtt_uint8 * data, stbtt_uint32 fontstart, const char * tag)
#endif
{
stbtt_int32 num_tables = ttUSHORT(data, fontstart + 4);
stbtt_uint32 tabledir = fontstart + 12;
stbtt_int32 i;
for(i = 0; i < num_tables; ++i) {
stbtt_uint32 loc = tabledir + 16 * i;
#ifdef STBTT_STREAM_TYPE
stbtt_uint8 buf[4];
STBTT_STREAM_SEEK(data, loc + 0);
STBTT_STREAM_READ(data, buf, 4);
if(stbtt_tag(buf, tag))
return ttULONG(data, loc + 8);
#else
if(stbtt_tag(data + loc + 0, tag))
return ttULONG(data, loc + 8);
#endif
}
return 0;
}
#ifdef STBTT_STREAM_TYPE
static int stbtt_GetFontOffsetForIndex_internal(STBTT_STREAM_TYPE font_collection, int index)
#else
static int stbtt_GetFontOffsetForIndex_internal(unsigned char * font_collection, int index)
#endif
{
// if it's just a font, there's only one valid index
if(stbtt__isfont(font_collection, 0))
return index == 0 ? 0 : -1;
// check if it's a TTC
#ifdef STBTT_STREAM_TYPE
stbtt_uint8 buf[4];
STBTT_STREAM_SEEK(font_collection, 0);
STBTT_STREAM_READ(font_collection, buf, 4);
if(stbtt_tag(buf, "ttcf")) {
#else
if(stbtt_tag(font_collection, "ttcf")) {
#endif
// version 1?
if(ttULONG(font_collection, 4) == 0x00010000 || ttULONG(font_collection, 4) == 0x00020000) {
stbtt_int32 n = ttLONG(font_collection, 8);
if(index >= n)
return -1;
return ttULONG(font_collection, 12 + index * 4);
}
}
return -1;
}
#ifdef STBTT_STREAM_TYPE
static int stbtt_GetNumberOfFonts_internal(STBTT_STREAM_TYPE font_collection)
#else
static int stbtt_GetNumberOfFonts_internal(unsigned char * font_collection)
#endif
{
// if it's just a font, there's only one valid font
if(stbtt__isfont(font_collection, 0))
return 1;
// check if it's a TTC
#ifdef STBTT_STREAM_TYPE
stbtt_uint8 buf[4];
STBTT_STREAM_SEEK(font_collection, 0);
STBTT_STREAM_READ(font_collection, buf, 4);
if(stbtt_tag(buf, "ttcf")) {
#else
if(stbtt_tag(font_collection, "ttcf")) {
#endif
// version 1?
if(ttULONG(font_collection, 4) == 0x00010000 || ttULONG(font_collection, 4) == 0x00020000) {
return ttLONG(font_collection, 8);
}
}
return 0;
}
static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict)
{
stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 };
stbtt__buf pdict;
stbtt__dict_get_ints(&fontdict, 18, 2, private_loc);
if(!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0);
pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]);
stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff);
if(!subrsoff) return stbtt__new_buf(NULL, 0);
stbtt__buf_seek(&cff, private_loc[1] + subrsoff);
return stbtt__cff_get_index(&cff);
}
// since most people won't use this, find this table the first time it's needed
static int stbtt__get_svg(stbtt_fontinfo * info)
{
stbtt_uint32 t;
if(info->svg < 0) {
t = stbtt__find_table(info->data, info->fontstart, "SVG ");
if(t) {
stbtt_uint32 offset = ttULONG(info->data, t + 2);
info->svg = t + offset;
}
else {
info->svg = 0;
}
}
return info->svg;
}
#ifdef STBTT_STREAM_TYPE
static int stbtt_InitFont_internal(stbtt_fontinfo * info, STBTT_STREAM_TYPE data, int fontstart)
#else
static int stbtt_InitFont_internal(stbtt_fontinfo * info, unsigned char * data, int fontstart)
#endif
{
stbtt_uint32 cmap, t;
stbtt_int32 i, numTables;
info->data = data;
info->fontstart = fontstart;
info->cff = stbtt__new_buf(NULL, 0);
cmap = stbtt__find_table(data, fontstart, "cmap"); // required
info->loca = stbtt__find_table(data, fontstart, "loca"); // required
info->head = stbtt__find_table(data, fontstart, "head"); // required
info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required
info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required
if(!cmap || !info->head || !info->hhea || !info->hmtx)
return 0;
if(info->glyf) {
// required for truetype
if(!info->loca) return 0;
}
else {
// initialization for CFF / Type2 fonts (OTF)
stbtt__buf b, topdict, topdictidx;
stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0;
stbtt_uint32 cff;
cff = stbtt__find_table(data, fontstart, "CFF ");
if(!cff) return 0;
info->fontdicts = stbtt__new_buf(NULL, 0);
info->fdselect = stbtt__new_buf(NULL, 0);
// @TODO this should use size from table (not 512MB)
#ifdef STBTT_STREAM_TYPE
info->cff = stbtt__new_buf(info->data, 512 * 1024 * 1024);
info->cff.offset = cff;
#else
info->cff = stbtt__new_buf(info->data + cff, 512 * 1024 * 1024);
#endif
b = info->cff;
// read the header
stbtt__buf_skip(&b, 2);
stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize
// @TODO the name INDEX could list multiple fonts,
// but we just use the first one.
stbtt__cff_get_index(&b); // name INDEX
topdictidx = stbtt__cff_get_index(&b);
topdict = stbtt__cff_index_get(topdictidx, 0);
stbtt__cff_get_index(&b); // string INDEX
info->gsubrs = stbtt__cff_get_index(&b);
stbtt__dict_get_ints(&topdict, 17, 1, &charstrings);
stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype);
stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff);
stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff);
info->subrs = stbtt__get_subrs(b, topdict);
// we only support Type 2 charstrings
if(cstype != 2) return 0;
if(charstrings == 0) return 0;
if(fdarrayoff) {
// looks like a CID font
if(!fdselectoff) return 0;
stbtt__buf_seek(&b, fdarrayoff);
info->fontdicts = stbtt__cff_get_index(&b);
info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size - fdselectoff);
}
stbtt__buf_seek(&b, charstrings);
info->charstrings = stbtt__cff_get_index(&b);
}
t = stbtt__find_table(data, fontstart, "maxp");
if(t)
info->numGlyphs = ttUSHORT(data, t + 4);
else
info->numGlyphs = 0xffff;
info->svg = -1;
// find a cmap encoding table we understand *now* to avoid searching
// later. (todo: could make this installable)
// the same regardless of glyph.
numTables = ttUSHORT(data, cmap + 2);
info->index_map = 0;
for(i = 0; i < numTables; ++i) {
stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
// find an encoding we understand:
switch(ttUSHORT(data, encoding_record)) {
case STBTT_PLATFORM_ID_MICROSOFT:
switch(ttUSHORT(data, encoding_record + 2)) {
case STBTT_MS_EID_UNICODE_BMP:
case STBTT_MS_EID_UNICODE_FULL:
// MS/Unicode
info->index_map = cmap + ttULONG(data, encoding_record + 4);
break;
}
break;
case STBTT_PLATFORM_ID_UNICODE:
// Mac/iOS has these
// all the encodingIDs are unicode, so we don't bother to check it
info->index_map = cmap + ttULONG(data, encoding_record + 4);
break;
}
}
if(info->index_map == 0)
return 0;
info->indexToLocFormat = ttUSHORT(data, info->head + 50);
return 1;
}
STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo * info, int unicode_codepoint)
{
#ifdef STBTT_STREAM_TYPE
STBTT_STREAM_TYPE data = info->data;
#else
stbtt_uint8 * data = info->data;
#endif
stbtt_uint32 index_map = info->index_map;
stbtt_uint16 format = ttUSHORT(data, index_map + 0);
if(format == 0) { // apple byte encoding
stbtt_int32 bytes = ttUSHORT(data, index_map + 2);
if(unicode_codepoint < bytes - 6)
return ttBYTE(data, index_map + 6 + unicode_codepoint);
return 0;
}
else if(format == 6) {
stbtt_uint32 first = ttUSHORT(data, index_map + 6);
stbtt_uint32 count = ttUSHORT(data, index_map + 8);
if((stbtt_uint32)unicode_codepoint >= first && (stbtt_uint32)unicode_codepoint < first + count)
return ttUSHORT(data, index_map + 10 + (unicode_codepoint - first) * 2);
return 0;
}
else if(format == 2) {
STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
return 0;
}
else if(format == 4) { // standard mapping for windows fonts: binary search collection of ranges
stbtt_uint16 segcount = ttUSHORT(data, index_map + 6) >> 1;
stbtt_uint16 searchRange = ttUSHORT(data, index_map + 8) >> 1;
stbtt_uint16 entrySelector = ttUSHORT(data, index_map + 10);
stbtt_uint16 rangeShift = ttUSHORT(data, index_map + 12) >> 1;
// do a binary search of the segments
stbtt_uint32 endCount = index_map + 14;
stbtt_uint32 search = endCount;
if(unicode_codepoint > 0xffff)
return 0;
// they lie from endCount .. endCount + segCount
// but searchRange is the nearest power of two, so...
if(unicode_codepoint >= ttUSHORT(data, search + rangeShift * 2))
search += rangeShift * 2;
// now decrement to bias correctly to find smallest
search -= 2;
while(entrySelector) {
stbtt_uint16 end;
searchRange >>= 1;
end = ttUSHORT(data, search + searchRange * 2);
if(unicode_codepoint > end)
search += searchRange * 2;
--entrySelector;
}
search += 2;
{
stbtt_uint16 offset, start, last;
stbtt_uint16 item = (stbtt_uint16)((search - endCount) >> 1);
start = ttUSHORT(data, index_map + 14 + segcount * 2 + 2 + 2 * item);
last = ttUSHORT(data, endCount + 2 * item);
if(unicode_codepoint < start || unicode_codepoint > last)
return 0;
offset = ttUSHORT(data, index_map + 14 + segcount * 6 + 2 + 2 * item);
if(offset == 0)
return (stbtt_uint16)(unicode_codepoint + ttSHORT(data, index_map + 14 + segcount * 4 + 2 + 2 * item));
return ttUSHORT(data, offset + (unicode_codepoint - start) * 2 + index_map + 14 + segcount * 6 + 2 + 2 * item);
}
}
else if(format == 12 || format == 13) {
stbtt_uint32 ngroups = ttULONG(data, index_map + 12);
stbtt_int32 low, high;
low = 0;
high = (stbtt_int32)ngroups;
// Binary search the right group.
while(low < high) {
stbtt_int32 mid = low + ((high - low) >> 1); // rounds down, so low <= mid < high
stbtt_uint32 start_char = ttULONG(data, index_map + 16 + mid * 12);
stbtt_uint32 end_char = ttULONG(data, index_map + 16 + mid * 12 + 4);
if((stbtt_uint32)unicode_codepoint < start_char)
high = mid;
else if((stbtt_uint32)unicode_codepoint > end_char)
low = mid + 1;
else {
stbtt_uint32 start_glyph = ttULONG(data, index_map + 16 + mid * 12 + 8);
if(format == 12)
return start_glyph + unicode_codepoint - start_char;
else // format == 13
return start_glyph;
}
}
return 0; // not found
}
// @TODO
STBTT_assert(0);
return 0;
}
STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo * info, int unicode_codepoint, stbtt_vertex * *vertices)
{
return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
}
static void stbtt_setvertex(stbtt_vertex * v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx,
stbtt_int32 cy)
{
v->type = type;
v->x = (stbtt_int16)x;
v->y = (stbtt_int16)y;
v->cx = (stbtt_int16)cx;
v->cy = (stbtt_int16)cy;
}
static int stbtt__GetGlyfOffset(const stbtt_fontinfo * info, int glyph_index)
{
int g1, g2;
STBTT_assert(!info->cff.size);
if(glyph_index >= info->numGlyphs) return -1; // glyph index out of range
if(info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format
if(info->indexToLocFormat == 0) {
g1 = info->glyf + ttUSHORT(info->data, info->loca + glyph_index * 2) * 2;
g2 = info->glyf + ttUSHORT(info->data, info->loca + glyph_index * 2 + 2) * 2;
}
else {
g1 = info->glyf + ttULONG(info->data, info->loca + glyph_index * 4);
g2 = info->glyf + ttULONG(info->data, info->loca + glyph_index * 4 + 4);
}
return g1 == g2 ? -1 : g1; // if length is 0, return -1
}
static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo * info, int glyph_index, int * x0, int * y0, int * x1, int * y1);
STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo * info, int glyph_index, int * x0, int * y0, int * x1, int * y1)
{
if(info->cff.size) {
stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1);
}
else {
int g = stbtt__GetGlyfOffset(info, glyph_index);
if(g < 0) return 0;
if(x0) *x0 = ttSHORT(info->data, g + 2);
if(y0) *y0 = ttSHORT(info->data, g + 4);
if(x1) *x1 = ttSHORT(info->data, g + 6);
if(y1) *y1 = ttSHORT(info->data, g + 8);
}
return 1;
}
STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo * info, int codepoint, int * x0, int * y0, int * x1, int * y1)
{
return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info, codepoint), x0, y0, x1, y1);
}
STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo * info, int glyph_index)
{
stbtt_int16 numberOfContours;
int g;
if(info->cff.size)
return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0;
g = stbtt__GetGlyfOffset(info, glyph_index);
if(g < 0) return 1;
numberOfContours = ttSHORT(info->data, g);
return numberOfContours == 0;
}
static int stbtt__close_shape(stbtt_vertex * vertices, int num_vertices, int was_off, int start_off,
stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
{
if(start_off) {
if(was_off)
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx + scx) >> 1, (cy + scy) >> 1, cx, cy);
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx, sy, scx, scy);
}
else {
if(was_off)
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx, sy, cx, cy);
else
stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, sx, sy, 0, 0);
}
return num_vertices;
}
static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo * info, int glyph_index, stbtt_vertex * *pvertices)
{
stbtt_int16 numberOfContours;
stbtt_uint32 endPtsOfContours;
#ifdef STBTT_STREAM_TYPE
STBTT_STREAM_TYPE data = info->data;
#else
stbtt_uint8 * data = info->data;
#endif
stbtt_vertex * vertices = 0;
int num_vertices = 0;
int g = stbtt__GetGlyfOffset(info, glyph_index);
*pvertices = NULL;
if(g < 0) return 0;
numberOfContours = ttSHORT(data, g);
if(numberOfContours > 0) {
stbtt_uint8 flags = 0, flagcount;
stbtt_int32 ins, i, j = 0, m, n, next_move, was_off = 0, off, start_off = 0;
stbtt_int32 x, y, cx, cy, sx, sy, scx, scy;
stbtt_uint32 points;
endPtsOfContours = (g + 10);
ins = ttUSHORT(data, g + 10 + numberOfContours * 2);
points = g + 10 + numberOfContours * 2 + 2 + ins;
n = 1 + ttUSHORT(data, endPtsOfContours + numberOfContours * 2 - 2);
m = n + 2 * numberOfContours; // a loose bound on how many vertices we might need
vertices = (stbtt_vertex *)STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
if(vertices == 0)
return 0;
next_move = 0;
flagcount = 0;
// in first pass, we load uninterpreted data into the allocated array
// above, shifted to the end of the array so we won't overwrite it when
// we create our final data starting from the front
off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated
// first load flags
for(i = 0; i < n; ++i) {
if(flagcount == 0) {
flags = ttBYTE(data, points++);
if(flags & 8)
flagcount = ttBYTE(data, points++);
}
else
--flagcount;
vertices[off + i].type = flags;
}
// now load x coordinates
x = 0;
for(i = 0; i < n; ++i) {
flags = vertices[off + i].type;
if(flags & 2) {
stbtt_int16 dx = ttBYTE(data, points++);
x += (flags & 16) ? dx : -dx; // ???
}
else {
if(!(flags & 16)) {
x = x + (stbtt_int16)(ttBYTE(data, points) * 256 + ttBYTE(data, points + 1));
points += 2;
}
}
vertices[off + i].x = (stbtt_int16)x;
}
// now load y coordinates
y = 0;
for(i = 0; i < n; ++i) {
flags = vertices[off + i].type;
if(flags & 4) {
stbtt_int16 dy = ttBYTE(data, points++);
y += (flags & 32) ? dy : -dy; // ???
}
else {
if(!(flags & 32)) {
y = y + (stbtt_int16)(ttBYTE(data, points) * 256 + ttBYTE(data, points + 1));
points += 2;
}
}
vertices[off + i].y = (stbtt_int16)y;
}
// now convert them to our format
num_vertices = 0;
sx = sy = cx = cy = scx = scy = 0;
for(i = 0; i < n; ++i) {
flags = vertices[off + i].type;
x = (stbtt_int16)vertices[off + i].x;
y = (stbtt_int16)vertices[off + i].y;
if(next_move == i) {
if(i != 0)
num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy);
// now start the new one
start_off = !(flags & 1);
if(start_off) {
// if we start off with an off-curve point, then when we need to find a point on the curve
// where we can start, and we need to save some state for when we wraparound.
scx = x;
scy = y;
if(!(vertices[off + i + 1].type & 1)) {
// next point is also a curve point, so interpolate an on-point curve
sx = (x + (stbtt_int32)vertices[off + i + 1].x) >> 1;
sy = (y + (stbtt_int32)vertices[off + i + 1].y) >> 1;
}
else {
// otherwise just use the next point as our start point
sx = (stbtt_int32)vertices[off + i + 1].x;
sy = (stbtt_int32)vertices[off + i + 1].y;
++i; // we're using point i+1 as the starting point, so skip it
}
}
else {
sx = x;
sy = y;
}
stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove, sx, sy, 0, 0);
was_off = 0;
next_move = 1 + ttUSHORT(data, endPtsOfContours + j * 2);
++j;
}
else {
if(!(flags & 1)) { // if it's a curve
if(was_off) // two off-curve control points in a row means interpolate an on-curve midpoint
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx + x) >> 1, (cy + y) >> 1, cx, cy);
cx = x;
cy = y;
was_off = 1;
}
else {
if(was_off)
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x, y, cx, cy);
else
stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x, y, 0, 0);
was_off = 0;
}
}
}
num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy);
}
else if(numberOfContours < 0) {
// Compound shapes.
int more = 1;
stbtt_uint32 comp = g + 10;
num_vertices = 0;
vertices = 0;
while(more) {
stbtt_uint16 flags, gidx;
int comp_num_verts = 0, i;
stbtt_vertex * comp_verts = 0, * tmp = 0;
float mtx[6] = { 1, 0, 0, 1, 0, 0 }, m, n;
flags = ttSHORT(data, comp);
comp += 2;
gidx = ttSHORT(data, comp);
comp += 2;
if(flags & 2) { // XY values
if(flags & 1) { // shorts
mtx[4] = ttSHORT(data, comp);
comp += 2;
mtx[5] = ttSHORT(data, comp);
comp += 2;
}
else {
mtx[4] = ttCHAR(data, comp);
comp += 1;
mtx[5] = ttCHAR(data, comp);
comp += 1;
}
}
else {
// @TODO handle matching point
STBTT_assert(0);
}
if(flags & (1 << 3)) { // WE_HAVE_A_SCALE
mtx[0] = mtx[3] = ttSHORT(data, comp) / 16384.0f;
comp += 2;
mtx[1] = mtx[2] = 0;
}
else if(flags & (1 << 6)) { // WE_HAVE_AN_X_AND_YSCALE
mtx[0] = ttSHORT(data, comp) / 16384.0f;
comp += 2;
mtx[1] = mtx[2] = 0;
mtx[3] = ttSHORT(data, comp) / 16384.0f;
comp += 2;
}
else if(flags & (1 << 7)) { // WE_HAVE_A_TWO_BY_TWO
mtx[0] = ttSHORT(data, comp) / 16384.0f;
comp += 2;
mtx[1] = ttSHORT(data, comp) / 16384.0f;
comp += 2;
mtx[2] = ttSHORT(data, comp) / 16384.0f;
comp += 2;
mtx[3] = ttSHORT(data, comp) / 16384.0f;
comp += 2;
}
// Find transformation scales.
m = (float)STBTT_sqrt(mtx[0] * mtx[0] + mtx[1] * mtx[1]);
n = (float)STBTT_sqrt(mtx[2] * mtx[2] + mtx[3] * mtx[3]);
// Get indexed glyph.
comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
if(comp_num_verts > 0) {
// Transform vertices.
for(i = 0; i < comp_num_verts; ++i) {
stbtt_vertex * v = &comp_verts[i];
stbtt_vertex_type x, y;
x = v->x;
y = v->y;
v->x = (stbtt_vertex_type)(m * (mtx[0] * x + mtx[2] * y + mtx[4]));
v->y = (stbtt_vertex_type)(n * (mtx[1] * x + mtx[3] * y + mtx[5]));
x = v->cx;
y = v->cy;
v->cx = (stbtt_vertex_type)(m * (mtx[0] * x + mtx[2] * y + mtx[4]));
v->cy = (stbtt_vertex_type)(n * (mtx[1] * x + mtx[3] * y + mtx[5]));
}
// Append vertices.
tmp = (stbtt_vertex *)STBTT_malloc((num_vertices + comp_num_verts) * sizeof(stbtt_vertex), info->userdata);
if(!tmp) {
if(vertices) STBTT_free(vertices, info->userdata);
if(comp_verts) STBTT_free(comp_verts, info->userdata);
return 0;
}
if(num_vertices > 0 && vertices) STBTT_memcpy(tmp, vertices, num_vertices * sizeof(stbtt_vertex));
STBTT_memcpy(tmp + num_vertices, comp_verts, comp_num_verts * sizeof(stbtt_vertex));
if(vertices) STBTT_free(vertices, info->userdata);
vertices = tmp;
STBTT_free(comp_verts, info->userdata);
num_vertices += comp_num_verts;
}
// More components ?
more = flags & (1 << 5);
}
}
else {
// numberOfCounters == 0, do nothing
}
*pvertices = vertices;
return num_vertices;
}
typedef struct {
int bounds;
int started;
float first_x, first_y;
float x, y;
stbtt_int32 min_x, max_x, min_y, max_y;
stbtt_vertex * pvertices;
int num_vertices;
} stbtt__csctx;
#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0}
static void stbtt__track_vertex(stbtt__csctx * c, stbtt_int32 x, stbtt_int32 y)
{
if(x > c->max_x || !c->started) c->max_x = x;
if(y > c->max_y || !c->started) c->max_y = y;
if(x < c->min_x || !c->started) c->min_x = x;
if(y < c->min_y || !c->started) c->min_y = y;
c->started = 1;
}
static void stbtt__csctx_v(stbtt__csctx * c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx,
stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1)
{
if(c->bounds) {
stbtt__track_vertex(c, x, y);
if(type == STBTT_vcubic) {
stbtt__track_vertex(c, cx, cy);
stbtt__track_vertex(c, cx1, cy1);
}
}
else {
stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy);
c->pvertices[c->num_vertices].cx1 = (stbtt_int16)cx1;
c->pvertices[c->num_vertices].cy1 = (stbtt_int16)cy1;
}
c->num_vertices++;
}
static void stbtt__csctx_close_shape(stbtt__csctx * ctx)
{
if(ctx->first_x != ctx->x || ctx->first_y != ctx->y)
stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0);
}
static void stbtt__csctx_rmove_to(stbtt__csctx * ctx, float dx, float dy)
{
stbtt__csctx_close_shape(ctx);
ctx->first_x = ctx->x = ctx->x + dx;
ctx->first_y = ctx->y = ctx->y + dy;
stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
}
static void stbtt__csctx_rline_to(stbtt__csctx * ctx, float dx, float dy)
{
ctx->x += dx;
ctx->y += dy;
stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
}
static void stbtt__csctx_rccurve_to(stbtt__csctx * ctx, float dx1, float dy1, float dx2, float dy2, float dx3,
float dy3)
{
float cx1 = ctx->x + dx1;
float cy1 = ctx->y + dy1;
float cx2 = cx1 + dx2;
float cy2 = cy1 + dy2;
ctx->x = cx2 + dx3;
ctx->y = cy2 + dy3;
stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2);
}
static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n)
{
int count = stbtt__cff_index_count(&idx);
int bias = 107;
if(count >= 33900)
bias = 32768;
else if(count >= 1240)
bias = 1131;
n += bias;
if(n < 0 || n >= count)
return stbtt__new_buf(NULL, 0);
return stbtt__cff_index_get(idx, n);
}
static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo * info, int glyph_index)
{
stbtt__buf fdselect = info->fdselect;
int nranges, start, end, v, fmt, fdselector = -1, i;
stbtt__buf_seek(&fdselect, 0);
fmt = stbtt__buf_get8(&fdselect);
if(fmt == 0) {
// untested
stbtt__buf_skip(&fdselect, glyph_index);
fdselector = stbtt__buf_get8(&fdselect);
}
else if(fmt == 3) {
nranges = stbtt__buf_get16(&fdselect);
start = stbtt__buf_get16(&fdselect);
for(i = 0; i < nranges; i++) {
v = stbtt__buf_get8(&fdselect);
end = stbtt__buf_get16(&fdselect);
if(glyph_index >= start && glyph_index < end) {
fdselector = v;
break;
}
start = end;
}
}
if(fdselector == -1) stbtt__new_buf(NULL, 0);
return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector));
}
static int stbtt__run_charstring(const stbtt_fontinfo * info, int glyph_index, stbtt__csctx * c)
{
int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0;
int has_subrs = 0, clear_stack;
float s[48];
stbtt__buf subr_stack[10], subrs = info->subrs, b;
float f;
#define STBTT__CSERR(s) (0)
// this currently ignores the initial width value, which isn't needed if we have hmtx
b = stbtt__cff_index_get(info->charstrings, glyph_index);
while(b.cursor < b.size) {
i = 0;
clear_stack = 1;
b0 = stbtt__buf_get8(&b);
switch(b0) {
// @TODO implement hinting
case 0x13: // hintmask
case 0x14: // cntrmask
if(in_header)
maskbits += (sp / 2); // implicit "vstem"
in_header = 0;
stbtt__buf_skip(&b, (maskbits + 7) / 8);
break;
case 0x01: // hstem
case 0x03: // vstem
case 0x12: // hstemhm
case 0x17: // vstemhm
maskbits += (sp / 2);
break;
case 0x15: // rmoveto
in_header = 0;
if(sp < 2) return STBTT__CSERR("rmoveto stack");
stbtt__csctx_rmove_to(c, s[sp - 2], s[sp - 1]);
break;
case 0x04: // vmoveto
in_header = 0;
if(sp < 1) return STBTT__CSERR("vmoveto stack");
stbtt__csctx_rmove_to(c, 0, s[sp - 1]);
break;
case 0x16: // hmoveto
in_header = 0;
if(sp < 1) return STBTT__CSERR("hmoveto stack");
stbtt__csctx_rmove_to(c, s[sp - 1], 0);
break;
case 0x05: // rlineto
if(sp < 2) return STBTT__CSERR("rlineto stack");
for(; i + 1 < sp; i += 2)
stbtt__csctx_rline_to(c, s[i], s[i + 1]);
break;
// hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical
// starting from a different place.
case 0x07: // vlineto
if(sp < 1) return STBTT__CSERR("vlineto stack");
goto vlineto;
case 0x06: // hlineto
if(sp < 1) return STBTT__CSERR("hlineto stack");
for(;;) {
if(i >= sp) break;
stbtt__csctx_rline_to(c, s[i], 0);
i++;
vlineto:
if(i >= sp) break;
stbtt__csctx_rline_to(c, 0, s[i]);
i++;
}
break;
case 0x1F: // hvcurveto
if(sp < 4) return STBTT__CSERR("hvcurveto stack");
goto hvcurveto;
case 0x1E: // vhcurveto
if(sp < 4) return STBTT__CSERR("vhcurveto stack");
for(;;) {
if(i + 3 >= sp) break;
stbtt__csctx_rccurve_to(c, 0, s[i], s[i + 1], s[i + 2], s[i + 3], (sp - i == 5) ? s[i + 4] : 0.0f);
i += 4;
hvcurveto:
if(i + 3 >= sp) break;
stbtt__csctx_rccurve_to(c, s[i], 0, s[i + 1], s[i + 2], (sp - i == 5) ? s[i + 4] : 0.0f, s[i + 3]);
i += 4;
}
break;
case 0x08: // rrcurveto
if(sp < 6) return STBTT__CSERR("rcurveline stack");
for(; i + 5 < sp; i += 6)
stbtt__csctx_rccurve_to(c, s[i], s[i + 1], s[i + 2], s[i + 3], s[i + 4], s[i + 5]);
break;
case 0x18: // rcurveline
if(sp < 8) return STBTT__CSERR("rcurveline stack");
for(; i + 5 < sp - 2; i += 6)
stbtt__csctx_rccurve_to(c, s[i], s[i + 1], s[i + 2], s[i + 3], s[i + 4], s[i + 5]);
if(i + 1 >= sp) return STBTT__CSERR("rcurveline stack");
stbtt__csctx_rline_to(c, s[i], s[i + 1]);
break;
case 0x19: // rlinecurve
if(sp < 8) return STBTT__CSERR("rlinecurve stack");
for(; i + 1 < sp - 6; i += 2)
stbtt__csctx_rline_to(c, s[i], s[i + 1]);
if(i + 5 >= sp) return STBTT__CSERR("rlinecurve stack");
stbtt__csctx_rccurve_to(c, s[i], s[i + 1], s[i + 2], s[i + 3], s[i + 4], s[i + 5]);
break;
case 0x1A: // vvcurveto
case 0x1B: // hhcurveto
if(sp < 4) return STBTT__CSERR("(vv|hh)curveto stack");
f = 0.0;
if(sp & 1) {
f = s[i];
i++;
}
for(; i + 3 < sp; i += 4) {
if(b0 == 0x1B)
stbtt__csctx_rccurve_to(c, s[i], f, s[i + 1], s[i + 2], s[i + 3], 0.0);
else
stbtt__csctx_rccurve_to(c, f, s[i], s[i + 1], s[i + 2], 0.0, s[i + 3]);
f = 0.0;
}
break;
case 0x0A: // callsubr
if(!has_subrs) {
if(info->fdselect.size)
subrs = stbtt__cid_get_glyph_subrs(info, glyph_index);
has_subrs = 1;
}
// FALLTHROUGH
case 0x1D: // callgsubr
if(sp < 1) return STBTT__CSERR("call(g|)subr stack");
v = (int)s[--sp];
if(subr_stack_height >= 10) return STBTT__CSERR("recursion limit");
subr_stack[subr_stack_height++] = b;
b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v);
if(b.size == 0) return STBTT__CSERR("subr not found");
b.cursor = 0;
clear_stack = 0;
break;
case 0x0B: // return
if(subr_stack_height <= 0) return STBTT__CSERR("return outside subr");
b = subr_stack[--subr_stack_height];
clear_stack = 0;
break;
case 0x0E: // endchar
stbtt__csctx_close_shape(c);
return 1;
case 0x0C: { // two-byte escape
float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6;
float dx, dy;
int b1 = stbtt__buf_get8(&b);
switch(b1) {
// @TODO These "flex" implementations ignore the flex-depth and resolution,
// and always draw beziers.
case 0x22: // hflex
if(sp < 7) return STBTT__CSERR("hflex stack");
dx1 = s[0];
dx2 = s[1];
dy2 = s[2];
dx3 = s[3];
dx4 = s[4];
dx5 = s[5];
dx6 = s[6];
stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0);
stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0);
break;
case 0x23: // flex
if(sp < 13) return STBTT__CSERR("flex stack");
dx1 = s[0];
dy1 = s[1];
dx2 = s[2];
dy2 = s[3];
dx3 = s[4];
dy3 = s[5];
dx4 = s[6];
dy4 = s[7];
dx5 = s[8];
dy5 = s[9];
dx6 = s[10];
dy6 = s[11];
//fd is s[12]
stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
break;
case 0x24: // hflex1
if(sp < 9) return STBTT__CSERR("hflex1 stack");
dx1 = s[0];
dy1 = s[1];
dx2 = s[2];
dy2 = s[3];
dx3 = s[4];
dx4 = s[5];
dx5 = s[6];
dy5 = s[7];
dx6 = s[8];
stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0);
stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1 + dy2 + dy5));
break;
case 0x25: // flex1
if(sp < 11) return STBTT__CSERR("flex1 stack");
dx1 = s[0];
dy1 = s[1];
dx2 = s[2];
dy2 = s[3];
dx3 = s[4];
dy3 = s[5];
dx4 = s[6];
dy4 = s[7];
dx5 = s[8];
dy5 = s[9];
dx6 = dy6 = s[10];
dx = dx1 + dx2 + dx3 + dx4 + dx5;
dy = dy1 + dy2 + dy3 + dy4 + dy5;
if(STBTT_fabs(dx) > STBTT_fabs(dy))
dy6 = -dy;
else
dx6 = -dx;
stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
break;
default:
return STBTT__CSERR("unimplemented");
}
}
break;
default:
if(b0 != 255 && b0 != 28 && b0 < 32)
return STBTT__CSERR("reserved operator");
// push immediate
if(b0 == 255) {
f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000;
}
else {
stbtt__buf_skip(&b, -1);
f = (float)(stbtt_int16)stbtt__cff_int(&b);
}
if(sp >= 48) return STBTT__CSERR("push stack overflow");
s[sp++] = f;
clear_stack = 0;
break;
}
if(clear_stack) sp = 0;
}
return STBTT__CSERR("no endchar");
#undef STBTT__CSERR
}
static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo * info, int glyph_index, stbtt_vertex * *pvertices)
{
// runs the charstring twice, once to count and once to output (to avoid realloc)
stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1);
stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0);
if(stbtt__run_charstring(info, glyph_index, &count_ctx)) {
*pvertices = (stbtt_vertex *)STBTT_malloc(count_ctx.num_vertices * sizeof(stbtt_vertex), info->userdata);
output_ctx.pvertices = *pvertices;
if(stbtt__run_charstring(info, glyph_index, &output_ctx)) {
STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices);
return output_ctx.num_vertices;
}
}
*pvertices = NULL;
return 0;
}
static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo * info, int glyph_index, int * x0, int * y0, int * x1, int * y1)
{
stbtt__csctx c = STBTT__CSCTX_INIT(1);
int r = stbtt__run_charstring(info, glyph_index, &c);
if(x0) *x0 = r ? c.min_x : 0;
if(y0) *y0 = r ? c.min_y : 0;
if(x1) *x1 = r ? c.max_x : 0;
if(y1) *y1 = r ? c.max_y : 0;
return r ? c.num_vertices : 0;
}
STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo * info, int glyph_index, stbtt_vertex * *pvertices)
{
if(!info->cff.size)
return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices);
else
return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices);
}
STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo * info, int glyph_index, int * advanceWidth,
int * leftSideBearing)
{
stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data, info->hhea + 34);
if(glyph_index < numOfLongHorMetrics) {
if(advanceWidth) *advanceWidth = ttSHORT(info->data, info->hmtx + 4 * glyph_index);
if(leftSideBearing) *leftSideBearing = ttSHORT(info->data, info->hmtx + 4 * glyph_index + 2);
}
else {
if(advanceWidth) *advanceWidth = ttSHORT(info->data, info->hmtx + 4 * (numOfLongHorMetrics - 1));
if(leftSideBearing) *leftSideBearing = ttSHORT(info->data,
info->hmtx + 4 * numOfLongHorMetrics + 2 * (glyph_index - numOfLongHorMetrics));
}
}
STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo * info)
{
// we only look at the first table. it must be 'horizontal' and format 0.
if(!info->kern)
return 0;
if(ttUSHORT(info->data, 2 + info->kern) < 1) // number of tables, need at least 1
return 0;
if(ttUSHORT(info->data, 8 + info->kern) != 1) // horizontal flag must be set in format
return 0;
return ttUSHORT(info->data, 10 + info->kern);
}
STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo * info, stbtt_kerningentry * table, int table_length)
{
int k, length;
// we only look at the first table. it must be 'horizontal' and format 0.
if(!info->kern)
return 0;
if(ttUSHORT(info->data, 2 + info->kern) < 1) // number of tables, need at least 1
return 0;
if(ttUSHORT(info->data, 8 + info->kern) != 1) // horizontal flag must be set in format
return 0;
length = ttUSHORT(info->data, 10 + info->kern);
if(table_length < length)
length = table_length;
for(k = 0; k < length; k++) {
table[k].glyph1 = ttUSHORT(info->data, 18 + (k * 6) + info->kern);
table[k].glyph2 = ttUSHORT(info->data, 20 + (k * 6) + info->kern);
table[k].advance = ttSHORT(info->data, 22 + (k * 6) + info->kern);
}
return length;
}
static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo * info, int glyph1, int glyph2)
{
stbtt_uint32 needle, straw;
int l, r, m;
// we only look at the first table. it must be 'horizontal' and format 0.
if(!info->kern)
return 0;
if(ttUSHORT(info->data, info->kern + 2) < 1) // number of tables, need at least 1
return 0;
if(ttUSHORT(info->data, info->kern + 8) != 1) // horizontal flag must be set in format
return 0;
l = 0;
r = ttUSHORT(info->data, info->kern + 10) - 1;
needle = glyph1 << 16 | glyph2;
while(l <= r) {
m = (l + r) >> 1;
straw = ttULONG(info->data, info->kern + 18 + (m * 6)); // note: unaligned read
if(needle < straw)
r = m - 1;
else if(needle > straw)
l = m + 1;
else
return ttSHORT(info->data, info->kern + 22 + (m * 6));
}
return 0;
}
#ifdef STBTT_STREAM_TYPE
static stbtt_int32 stbtt__GetCoverageIndex(STBTT_STREAM_TYPE data, stbtt_uint32 coverageTable, int glyph)
#else
static stbtt_int32 stbtt__GetCoverageIndex(const stbtt_uint8 * data, stbtt_uint32 coverageTable, int glyph)
#endif
{
stbtt_uint16 coverageFormat = ttUSHORT(data, coverageTable);
switch(coverageFormat) {
case 1: {
stbtt_uint16 glyphCount = ttUSHORT(data, coverageTable + 2);
// Binary search.
stbtt_int32 l = 0, r = glyphCount - 1, m;
int straw, needle = glyph;
while(l <= r) {
stbtt_uint32 glyphArray = coverageTable + 4;
stbtt_uint16 glyphID;
m = (l + r) >> 1;
glyphID = ttUSHORT(data, glyphArray + 2 * m);
straw = glyphID;
if(needle < straw)
r = m - 1;
else if(needle > straw)
l = m + 1;
else {
return m;
}
}
break;
}
case 2: {
stbtt_uint16 rangeCount = ttUSHORT(data, coverageTable + 2);
stbtt_uint32 rangeArray = coverageTable + 4;
// Binary search.
stbtt_int32 l = 0, r = rangeCount - 1, m;
int strawStart, strawEnd, needle = glyph;
while(l <= r) {
stbtt_uint32 rangeRecord;
m = (l + r) >> 1;
rangeRecord = rangeArray + 6 * m;
strawStart = ttUSHORT(data, rangeRecord);
strawEnd = ttUSHORT(data, rangeRecord + 2);
if(needle < strawStart)
r = m - 1;
else if(needle > strawEnd)
l = m + 1;
else {
stbtt_uint16 startCoverageIndex = ttUSHORT(data, rangeRecord + 4);
return startCoverageIndex + glyph - strawStart;
}
}
break;
}
default:
return -1; // unsupported
}
return -1;
}
#ifdef STBTT_STREAM_TYPE
static stbtt_int32 stbtt__GetGlyphClass(STBTT_STREAM_TYPE data, stbtt_uint32 classDefTable, int glyph)
#else
static stbtt_int32 stbtt__GetGlyphClass(const stbtt_uint8 * data, stbtt_uint32 classDefTable, int glyph)
#endif
{
stbtt_uint16 classDefFormat = ttUSHORT(data, classDefTable);
switch(classDefFormat) {
case 1: {
stbtt_uint16 startGlyphID = ttUSHORT(data, classDefTable + 2);
stbtt_uint16 glyphCount = ttUSHORT(data, classDefTable + 4);
stbtt_uint32 classDef1ValueArray = classDefTable + 6;
if(glyph >= startGlyphID && glyph < startGlyphID + glyphCount)
return (stbtt_int32)ttUSHORT(data, classDef1ValueArray + 2 * (glyph - startGlyphID));
break;
}
case 2: {
stbtt_uint16 classRangeCount = ttUSHORT(data, classDefTable + 2);
stbtt_uint32 classRangeRecords = classDefTable + 4;
// Binary search.
stbtt_int32 l = 0, r = classRangeCount - 1, m;
int strawStart, strawEnd, needle = glyph;
while(l <= r) {
stbtt_uint32 classRangeRecord;
m = (l + r) >> 1;
classRangeRecord = classRangeRecords + 6 * m;
strawStart = ttUSHORT(data, classRangeRecord);
strawEnd = ttUSHORT(data, classRangeRecord + 2);
if(needle < strawStart)
r = m - 1;
else if(needle > strawEnd)
l = m + 1;
else
return (stbtt_int32)ttUSHORT(data, classRangeRecord + 4);
}
break;
}
default:
return -1; // Unsupported definition type, return an error.
}
// "All glyphs not assigned to a class fall into class 0". (OpenType spec)
return 0;
}
// Define to STBTT_assert(x) if you want to break on unimplemented formats.
#define STBTT_GPOS_TODO_assert(x)
static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo * info, int glyph1, int glyph2)
{
stbtt_uint16 lookupListOffset;
stbtt_uint32 lookupList;
stbtt_uint16 lookupCount;
#ifdef STBTT_STREAM_TYPE
STBTT_STREAM_TYPE data = info->data;
#else
const stbtt_uint8 * data = info->data;
#endif
stbtt_int32 i, sti;
if(!info->gpos) return 0;
if(ttUSHORT(data, 0 + info->gpos) != 1) return 0; // Major version 1
if(ttUSHORT(data, 2 + info->gpos) != 0) return 0; // Minor version 0
lookupListOffset = ttUSHORT(data, 8 + info->gpos);
lookupList = lookupListOffset;
lookupCount = ttUSHORT(data, lookupList);
for(i = 0; i < lookupCount; ++i) {
stbtt_uint16 lookupOffset = ttUSHORT(data, lookupList + 2 + 2 * i);
stbtt_uint32 lookupTable = lookupList + lookupOffset;
stbtt_uint16 lookupType = ttUSHORT(data, lookupTable);
stbtt_uint16 subTableCount = ttUSHORT(data, lookupTable + 4);
stbtt_uint32 subTableOffsets = lookupTable + 6;
if(lookupType != 2) // Pair Adjustment Positioning Subtable
continue;
for(sti = 0; sti < subTableCount; sti++) {
stbtt_uint16 subtableOffset = ttUSHORT(data, subTableOffsets + 2 * sti);
stbtt_uint32 table = lookupTable + subtableOffset;
stbtt_uint16 posFormat = ttUSHORT(data, table);
stbtt_uint16 coverageOffset = ttUSHORT(data, table + 2);
stbtt_int32 coverageIndex = stbtt__GetCoverageIndex(data, table + coverageOffset, glyph1);
if(coverageIndex == -1) continue;
switch(posFormat) {
case 1: {
stbtt_int32 l, r, m;
int straw, needle;
stbtt_uint16 valueFormat1 = ttUSHORT(data, table + 4);
stbtt_uint16 valueFormat2 = ttUSHORT(data, table + 6);
if(valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats?
stbtt_int32 valueRecordPairSizeInBytes = 2;
stbtt_uint16 pairSetCount = ttUSHORT(data, table + 8);
stbtt_uint16 pairPosOffset = ttUSHORT(data, table + 10 + 2 * coverageIndex);
stbtt_uint32 pairValueTable = table + pairPosOffset;
stbtt_uint16 pairValueCount = ttUSHORT(data, pairValueTable);
stbtt_uint32 pairValueArray = pairValueTable + 2;
if(coverageIndex >= pairSetCount) return 0;
needle = glyph2;
r = pairValueCount - 1;
l = 0;
// Binary search.
while(l <= r) {
stbtt_uint16 secondGlyph;
stbtt_uint32 pairValue;
m = (l + r) >> 1;
pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m;
secondGlyph = ttUSHORT(data, pairValue);
straw = secondGlyph;
if(needle < straw)
r = m - 1;
else if(needle > straw)
l = m + 1;
else {
stbtt_int16 xAdvance = ttSHORT(data, pairValue + 2);
return xAdvance;
}
}
}
else
return 0;
break;
}
case 2: {
stbtt_uint16 valueFormat1 = ttUSHORT(data, table + 4);
stbtt_uint16 valueFormat2 = ttUSHORT(data, table + 6);
if(valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats?
stbtt_uint16 classDef1Offset = ttUSHORT(data, table + 8);
stbtt_uint16 classDef2Offset = ttUSHORT(data, table + 10);
int glyph1class = stbtt__GetGlyphClass(data, table + classDef1Offset, glyph1);
int glyph2class = stbtt__GetGlyphClass(data, table + classDef2Offset, glyph2);
stbtt_uint16 class1Count = ttUSHORT(data, table + 12);
stbtt_uint16 class2Count = ttUSHORT(data, table + 14);
stbtt_uint32 class1Records, class2Records;
stbtt_int16 xAdvance;
if(glyph1class < 0 || glyph1class >= class1Count) return 0; // malformed
if(glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed
class1Records = table + 16;
class2Records = class1Records + 2 * (glyph1class * class2Count);
xAdvance = ttSHORT(data, class2Records + 2 * glyph2class);
return xAdvance;
}
else
return 0;
break;
}
default:
return 0; // Unsupported position format
}
}
}
return 0;
}
STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo * info, int g1, int g2)
{
int xAdvance = 0;
if(info->gpos)
xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2);
else if(info->kern)
xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2);
return xAdvance;
}
STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo * info, int ch1, int ch2)
{
if(!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs
return 0;
return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info, ch1), stbtt_FindGlyphIndex(info, ch2));
}
STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo * info, int codepoint, int * advanceWidth,
int * leftSideBearing)
{
stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info, codepoint), advanceWidth, leftSideBearing);
}
STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo * info, int * ascent, int * descent, int * lineGap)
{
if(ascent) *ascent = ttSHORT(info->data, info->hhea + 4);
if(descent) *descent = ttSHORT(info->data, info->hhea + 6);
if(lineGap) *lineGap = ttSHORT(info->data, info->hhea + 8);
}
STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo * info, int * typoAscent, int * typoDescent,
int * typoLineGap)
{
int tab = stbtt__find_table(info->data, info->fontstart, "OS/2");
if(!tab)
return 0;
if(typoAscent) *typoAscent = ttSHORT(info->data, tab + 68);
if(typoDescent) *typoDescent = ttSHORT(info->data, tab + 70);
if(typoLineGap) *typoLineGap = ttSHORT(info->data, tab + 72);
return 1;
}
STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo * info, int * x0, int * y0, int * x1, int * y1)
{
*x0 = ttSHORT(info->data, info->head + 36);
*y0 = ttSHORT(info->data, info->head + 38);
*x1 = ttSHORT(info->data, info->head + 40);
*y1 = ttSHORT(info->data, info->head + 42);
}
STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo * info, float height)
{
int fheight = ttSHORT(info->data, info->hhea + 4) - ttSHORT(info->data, info->hhea + 6);
return (float)height / fheight;
}
STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo * info, float pixels)
{
int unitsPerEm = ttUSHORT(info->data, info->head + 18);
return pixels / unitsPerEm;
}
STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo * info, stbtt_vertex * v)
{
STBTT_free(v, info->userdata);
}
STBTT_DEF stbtt_uint32 stbtt_FindSVGDoc(const stbtt_fontinfo * info, int gl)
{
int i;
stbtt_uint32 svg_doc_list = stbtt__get_svg((stbtt_fontinfo *)info);
int numEntries = ttUSHORT(info->data, svg_doc_list);
stbtt_uint32 svg_docs = svg_doc_list + 2;
for(i = 0; i < numEntries; i++) {
stbtt_uint32 svg_doc = svg_docs + (12 * i);
if((gl >= ttUSHORT(info->data, svg_doc)) && (gl <= ttUSHORT(info->data, svg_doc + 2)))
return svg_doc;
}
return 0;
}
STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo * info, int gl, stbtt_uint32 * svgOfs)
{
stbtt_uint32 svg_doc;
if(info->svg == 0)
return 0;
svg_doc = stbtt_FindSVGDoc(info, gl);
if(svg_doc != 0) {
*svgOfs = info->svg + ttULONG(info->data, svg_doc + 4);
return ttULONG(info->data, svg_doc + 8);
}
else {
return 0;
}
}
STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo * info, int unicode_codepoint, stbtt_uint32 * svgOfs)
{
return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svgOfs);
}
//////////////////////////////////////////////////////////////////////////////
//
// antialiasing software rasterizer
//
STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo * font, int glyph, float scale_x, float scale_y,
float shift_x, float shift_y, int * ix0, int * iy0, int * ix1, int * iy1)
{
int x0 = 0, y0 = 0, x1, y1; // =0 suppresses compiler warning
if(!stbtt_GetGlyphBox(font, glyph, &x0, &y0, &x1, &y1)) {
// e.g. space character
if(ix0) *ix0 = 0;
if(iy0) *iy0 = 0;
if(ix1) *ix1 = 0;
if(iy1) *iy1 = 0;
}
else {
// move to integral bboxes (treating pixels as little squares, what pixels get touched)?
if(ix0) *ix0 = STBTT_ifloor(x0 * scale_x + shift_x);
if(iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);
if(ix1) *ix1 = STBTT_iceil(x1 * scale_x + shift_x);
if(iy1) *iy1 = STBTT_iceil(-y0 * scale_y + shift_y);
}
}
STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo * font, int glyph, float scale_x, float scale_y, int * ix0,
int * iy0, int * ix1, int * iy1)
{
stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, 0.0f, 0.0f, ix0, iy0, ix1, iy1);
}
STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo * font, int codepoint, float scale_x,
float scale_y, float shift_x, float shift_y, int * ix0, int * iy0, int * ix1, int * iy1)
{
stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font, codepoint), scale_x, scale_y, shift_x, shift_y, ix0,
iy0, ix1, iy1);
}
STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo * font, int codepoint, float scale_x, float scale_y,
int * ix0, int * iy0, int * ix1, int * iy1)
{
stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y, 0.0f, 0.0f, ix0, iy0, ix1, iy1);
}
//////////////////////////////////////////////////////////////////////////////
//
// Rasterizer
typedef struct stbtt__hheap_chunk {
struct stbtt__hheap_chunk * next;
} stbtt__hheap_chunk;
typedef struct stbtt__hheap {
struct stbtt__hheap_chunk * head;
void * first_free;
int num_remaining_in_head_chunk;
} stbtt__hheap;
static void * stbtt__hheap_alloc(stbtt__hheap * hh, size_t size, void * userdata)
{
if(hh->first_free) {
void * p = hh->first_free;
hh->first_free = *(void **)p;
return p;
}
else {
if(hh->num_remaining_in_head_chunk == 0) {
int count = (size < 32 ? STBTT_HEAP_FACTOR_SIZE_32 : size < 128 ? STBTT_HEAP_FACTOR_SIZE_128 :
STBTT_HEAP_FACTOR_SIZE_DEFAULT);
stbtt__hheap_chunk * c = (stbtt__hheap_chunk *)STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata);
if(c == NULL)
return NULL;
c->next = hh->head;
hh->head = c;
hh->num_remaining_in_head_chunk = count;
}
--hh->num_remaining_in_head_chunk;
return (char *)(hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk;
}
}
static void stbtt__hheap_free(stbtt__hheap * hh, void * p)
{
*(void **)p = hh->first_free;
hh->first_free = p;
}
static void stbtt__hheap_cleanup(stbtt__hheap * hh, void * userdata)
{
stbtt__hheap_chunk * c = hh->head;
while(c) {
stbtt__hheap_chunk * n = c->next;
STBTT_free(c, userdata);
c = n;
}
}
typedef struct stbtt__edge {
float x0, y0, x1, y1;
int invert;
} stbtt__edge;
typedef struct stbtt__active_edge {
struct stbtt__active_edge * next;
#if STBTT_RASTERIZER_VERSION==1
int x, dx;
float ey;
int direction;
#elif STBTT_RASTERIZER_VERSION==2
float fx, fdx, fdy;
float direction;
float sy;
float ey;
#else
#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
#endif
} stbtt__active_edge;
#if STBTT_RASTERIZER_VERSION == 1
#define STBTT_FIXSHIFT 10
#define STBTT_FIX (1 << STBTT_FIXSHIFT)
#define STBTT_FIXMASK (STBTT_FIX-1)
static stbtt__active_edge * stbtt__new_active(stbtt__hheap * hh, stbtt__edge * e, int off_x, float start_point,
void * userdata)
{
stbtt__active_edge * z = (stbtt__active_edge *)stbtt__hheap_alloc(hh, sizeof(*z), userdata);
float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
STBTT_assert(z != NULL);
if(!z) return z;
// round dx down to avoid overshooting
if(dxdy < 0)
z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy);
else
z->dx = STBTT_ifloor(STBTT_FIX * dxdy);
z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point -
e->y0)); // use z->dx so when we offset later it's by the same amount
z->x -= off_x * STBTT_FIX;
z->ey = e->y1;
z->next = 0;
z->direction = e->invert ? 1 : -1;
return z;
}
#elif STBTT_RASTERIZER_VERSION == 2
static stbtt__active_edge * stbtt__new_active(stbtt__hheap * hh, stbtt__edge * e, int off_x, float start_point,
void * userdata)
{
stbtt__active_edge * z = (stbtt__active_edge *)stbtt__hheap_alloc(hh, sizeof(*z), userdata);
float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
STBTT_assert(z != NULL);
//STBTT_assert(e->y0 <= start_point);
if(!z) return z;
z->fdx = dxdy;
z->fdy = dxdy != 0.0f ? (1.0f / dxdy) : 0.0f;
z->fx = e->x0 + dxdy * (start_point - e->y0);
z->fx -= off_x;
z->direction = e->invert ? 1.0f : -1.0f;
z->sy = e->y0;
z->ey = e->y1;
z->next = 0;
return z;
}
#else
#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
#endif
#if STBTT_RASTERIZER_VERSION == 1
// note: this routine clips fills that extend off the edges... ideally this
// wouldn't happen, but it could happen if the truetype glyph bounding boxes
// are wrong, or if the user supplies a too-small bitmap
static void stbtt__fill_active_edges(unsigned char * scanline, int len, stbtt__active_edge * e, int max_weight)
{
// non-zero winding fill
int x0 = 0, w = 0;
while(e) {
if(w == 0) {
// if we're currently at zero, we need to record the edge start point
x0 = e->x;
w += e->direction;
}
else {
int x1 = e->x;
w += e->direction;
// if we went to zero, we need to draw
if(w == 0) {
int i = x0 >> STBTT_FIXSHIFT;
int j = x1 >> STBTT_FIXSHIFT;
if(i < len && j >= 0) {
if(i == j) {
// x0,x1 are the same pixel, so compute combined coverage
scanline[i] = scanline[i] + (stbtt_uint8)((x1 - x0) * max_weight >> STBTT_FIXSHIFT);
}
else {
if(i >= 0) // add antialiasing for x0
scanline[i] = scanline[i] + (stbtt_uint8)(((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT);
else
i = -1; // clip
if(j < len) // add antialiasing for x1
scanline[j] = scanline[j] + (stbtt_uint8)(((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT);
else
j = len; // clip
for(++i; i < j; ++i) // fill pixels between x0 and x1
scanline[i] = scanline[i] + (stbtt_uint8)max_weight;
}
}
}
}
e = e->next;
}
}
static void stbtt__rasterize_sorted_edges(stbtt__bitmap * result, stbtt__edge * e, int n, int vsubsample, int off_x,
int off_y, void * userdata)
{
stbtt__hheap hh = { 0, 0, 0 };
stbtt__active_edge * active = NULL;
int y, j = 0;
int max_weight = (255 / vsubsample); // weight per vertical scanline
int s; // vertical subsample index
unsigned char scanline_data[512], * scanline;
if(result->w > 512)
scanline = (unsigned char *)STBTT_malloc(result->w, userdata);
else
scanline = scanline_data;
y = off_y * vsubsample;
e[n].y0 = (off_y + result->h) * (float)vsubsample + 1;
while(j < result->h) {
STBTT_memset(scanline, 0, result->w);
for(s = 0; s < vsubsample; ++s) {
// find center of pixel for this scanline
float scan_y = y + 0.5f;
stbtt__active_edge ** step = &active;
// update all active edges;
// remove all active edges that terminate before the center of this scanline
while(*step) {
stbtt__active_edge * z = *step;
if(z->ey <= scan_y) {
*step = z->next; // delete from list
STBTT_assert(z->direction);
z->direction = 0;
stbtt__hheap_free(&hh, z);
}
else {
z->x += z->dx; // advance to position for current scanline
step = &((*step)->next); // advance through list
}
}
// resort the list if needed
for(;;) {
int changed = 0;
step = &active;
while(*step && (*step)->next) {
if((*step)->x > (*step)->next->x) {
stbtt__active_edge * t = *step;
stbtt__active_edge * q = t->next;
t->next = q->next;
q->next = t;
*step = q;
changed = 1;
}
step = &(*step)->next;
}
if(!changed) break;
}
// insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
while(e->y0 <= scan_y) {
if(e->y1 > scan_y) {
stbtt__active_edge * z = stbtt__new_active(&hh, e, off_x, scan_y, userdata);
if(z != NULL) {
// find insertion point
if(active == NULL)
active = z;
else if(z->x < active->x) {
// insert at front
z->next = active;
active = z;
}
else {
// find thing to insert AFTER
stbtt__active_edge * p = active;
while(p->next && p->next->x < z->x)
p = p->next;
// at this point, p->next->x is NOT < z->x
z->next = p->next;
p->next = z;
}
}
}
++e;
}
// now process all active edges in XOR fashion
if(active)
stbtt__fill_active_edges(scanline, result->w, active, max_weight);
++y;
}
STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
++j;
}
stbtt__hheap_cleanup(&hh, userdata);
if(scanline != scanline_data)
STBTT_free(scanline, userdata);
}
#elif STBTT_RASTERIZER_VERSION == 2
// the edge passed in here does not cross the vertical line at x or the vertical line at x+1
// (i.e. it has already been clipped to those)
static void stbtt__handle_clipped_edge(float * scanline, int x, stbtt__active_edge * e, float x0, float y0, float x1,
float y1)
{
if(y0 == y1) return;
STBTT_assert(y0 < y1);
STBTT_assert(e->sy <= e->ey);
if(y0 > e->ey) return;
if(y1 < e->sy) return;
if(y0 < e->sy) {
x0 += (x1 - x0) * (e->sy - y0) / (y1 - y0);
y0 = e->sy;
}
if(y1 > e->ey) {
x1 += (x1 - x0) * (e->ey - y1) / (y1 - y0);
y1 = e->ey;
}
if(x0 == x)
STBTT_assert(x1 <= x + 1);
else if(x0 == x + 1)
STBTT_assert(x1 >= x);
else if(x0 <= x)
STBTT_assert(x1 <= x);
else if(x0 >= x + 1)
STBTT_assert(x1 >= x + 1);
else
STBTT_assert(x1 >= x && x1 <= x + 1);
if(x0 <= x && x1 <= x)
scanline[x] += e->direction * (y1 - y0);
else if(x0 >= x + 1 && x1 >= x + 1) {
/*Nothing to do*/;
}
else {
STBTT_assert(x0 >= x && x0 <= x + 1 && x1 >= x && x1 <= x + 1);
scanline[x] += e->direction * (y1 - y0) * (1 - ((x0 - x) + (x1 - x)) / 2); // coverage = 1 - average x position
}
}
static float stbtt__sized_trapezoid_area(float height, float top_width, float bottom_width)
{
STBTT_assert(top_width >= 0);
STBTT_assert(bottom_width >= 0);
return (top_width + bottom_width) / 2.0f * height;
}
static float stbtt__position_trapezoid_area(float height, float tx0, float tx1, float bx0, float bx1)
{
return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0);
}
static float stbtt__sized_triangle_area(float height, float width)
{
return height * width / 2;
}
static void stbtt__fill_active_edges_new(float * scanline, float * scanline_fill, int len, stbtt__active_edge * e,
float y_top)
{
float y_bottom = y_top + 1;
while(e) {
// brute force every pixel
// compute intersection points with top & bottom
STBTT_assert(e->ey >= y_top);
if(e->fdx == 0) {
float x0 = e->fx;
if(x0 < len) {
if(x0 >= 0) {
stbtt__handle_clipped_edge(scanline, (int)x0, e, x0, y_top, x0, y_bottom);
stbtt__handle_clipped_edge(scanline_fill - 1, (int)x0 + 1, e, x0, y_top, x0, y_bottom);
}
else {
stbtt__handle_clipped_edge(scanline_fill - 1, 0, e, x0, y_top, x0, y_bottom);
}
}
}
else {
float x0 = e->fx;
float dx = e->fdx;
float xb = x0 + dx;
float x_top, x_bottom;
float sy0, sy1;
float dy = e->fdy;
STBTT_assert(e->sy <= y_bottom && e->ey >= y_top);
// compute endpoints of line segment clipped to this scanline (if the
// line segment starts on this scanline. x0 is the intersection of the
// line with y_top, but that may be off the line segment.
if(e->sy > y_top) {
x_top = x0 + dx * (e->sy - y_top);
sy0 = e->sy;
}
else {
x_top = x0;
sy0 = y_top;
}
if(e->ey < y_bottom) {
x_bottom = x0 + dx * (e->ey - y_top);
sy1 = e->ey;
}
else {
x_bottom = xb;
sy1 = y_bottom;
}
if(x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) {
// from here on, we don't have to range check x values
if((int)x_top == (int)x_bottom) {
float height;
// simple case, only spans one pixel
int x = (int)x_top;
height = (sy1 - sy0) * e->direction;
STBTT_assert(x >= 0 && x < len);
scanline[x] += stbtt__position_trapezoid_area(height, x_top, x + 1.0f, x_bottom, x + 1.0f);
scanline_fill[x] += height; // everything right of this pixel is filled
}
else {
int x, x1, x2;
float y_crossing, y_final, step, sign, area;
// covers 2+ pixels
if(x_top > x_bottom) {
// flip scanline vertically; signed area is the same
float t;
sy0 = y_bottom - (sy0 - y_top);
sy1 = y_bottom - (sy1 - y_top);
t = sy0, sy0 = sy1, sy1 = t;
t = x_bottom, x_bottom = x_top, x_top = t;
dx = -dx;
dy = -dy;
t = x0, x0 = xb, xb = t;
}
STBTT_assert(dy >= 0);
STBTT_assert(dx >= 0);
x1 = (int)x_top;
x2 = (int)x_bottom;
// compute intersection with y axis at x1+1
y_crossing = y_top + dy * (x1 + 1 - x0);
// compute intersection with y axis at x2
y_final = y_top + dy * (x2 - x0);
// x1 x_top x2 x_bottom
// y_top +------|-----+------------+------------+--------|---+------------+
// | | | | | |
// | | | | | |
// sy0 | Txxxxx|............|............|............|............|
// y_crossing | *xxxxx.......|............|............|............|
// | | xxxxx..|............|............|............|
// | | /- xx*xxxx........|............|............|
// | | dy < | xxxxxx..|............|............|
// y_final | | \- | xx*xxx.........|............|
// sy1 | | | | xxxxxB...|............|
// | | | | | |
// | | | | | |
// y_bottom +------------+------------+------------+------------+------------+
//
// goal is to measure the area covered by '.' in each pixel
// if x2 is right at the right edge of x1, y_crossing can blow up, github #1057
// @TODO: maybe test against sy1 rather than y_bottom?
if(y_crossing > y_bottom)
y_crossing = y_bottom;
sign = e->direction;
// area of the rectangle covered from sy0..y_crossing
area = sign * (y_crossing - sy0);
// area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing)
scanline[x1] += stbtt__sized_triangle_area(area, x1 + 1 - x_top);
// check if final y_crossing is blown up; no test case for this
if(y_final > y_bottom) {
y_final = y_bottom;
dy = (y_final - y_crossing) / (x2 - (x1 + 1)); // if denom=0, y_final = y_crossing, so y_final <= y_bottom
}
// in second pixel, area covered by line segment found in first pixel
// is always a rectangle 1 wide * the height of that line segment; this
// is exactly what the variable 'area' stores. it also gets a contribution
// from the line segment within it. the THIRD pixel will get the first
// pixel's rectangle contribution, the second pixel's rectangle contribution,
// and its own contribution. the 'own contribution' is the same in every pixel except
// the leftmost and rightmost, a trapezoid that slides down in each pixel.
// the second pixel's contribution to the third pixel will be the
// rectangle 1 wide times the height change in the second pixel, which is dy.
step = sign * dy * 1; // dy is dy/dx, change in y for every 1 change in x,
// which multiplied by 1-pixel-width is how much pixel area changes for each step in x
// so the area advances by 'step' every time
for(x = x1 + 1; x < x2; ++x) {
scanline[x] += area + step / 2; // area of trapezoid is 1*step/2
area += step;
}
STBTT_assert(STBTT_fabs(area) <= 1.01f); // accumulated error from area += step unless we round step down
STBTT_assert(sy1 > y_final - 0.01f);
// area covered in the last pixel is the rectangle from all the pixels to the left,
// plus the trapezoid filled by the line segment in this pixel all the way to the right edge
scanline[x2] += area + sign * stbtt__position_trapezoid_area(sy1 - y_final, (float)x2, x2 + 1.0f, x_bottom, x2 + 1.0f);
// the rest of the line is filled based on the total height of the line segment in this pixel
scanline_fill[x2] += sign * (sy1 - sy0);
}
}
else {
// if edge goes outside of box we're drawing, we require
// clipping logic. since this does not match the intended use
// of this library, we use a different, very slow brute
// force implementation
// note though that this does happen some of the time because
// x_top and x_bottom can be extrapolated at the top & bottom of
// the shape and actually lie outside the bounding box
int x;
for(x = 0; x < len; ++x) {
// cases:
//
// there can be up to two intersections with the pixel. any intersection
// with left or right edges can be handled by splitting into two (or three)
// regions. intersections with top & bottom do not necessitate case-wise logic.
//
// the old way of doing this found the intersections with the left & right edges,
// then used some simple logic to produce up to three segments in sorted order
// from top-to-bottom. however, this had a problem: if an x edge was epsilon
// across the x border, then the corresponding y position might not be distinct
// from the other y segment, and it might ignored as an empty segment. to avoid
// that, we need to explicitly produce segments based on x positions.
// rename variables to clearly-defined pairs
float y0 = y_top;
float x1 = (float)(x);
float x2 = (float)(x + 1);
float x3 = xb;
float y3 = y_bottom;
// x = e->x + e->dx * (y-y_top)
// (y-y_top) = (x - e->x) / e->dx
// y = (x - e->x) / e->dx + y_top
float y1 = (x - x0) / dx + y_top;
float y2 = (x + 1 - x0) / dx + y_top;
if(x0 < x1 && x3 > x2) { // three segments descending down-right
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1);
stbtt__handle_clipped_edge(scanline, x, e, x1, y1, x2, y2);
stbtt__handle_clipped_edge(scanline, x, e, x2, y2, x3, y3);
}
else if(x3 < x1 && x0 > x2) { // three segments descending down-left
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x2, y2);
stbtt__handle_clipped_edge(scanline, x, e, x2, y2, x1, y1);
stbtt__handle_clipped_edge(scanline, x, e, x1, y1, x3, y3);
}
else if(x0 < x1 && x3 > x1) { // two segments across x, down-right
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1);
stbtt__handle_clipped_edge(scanline, x, e, x1, y1, x3, y3);
}
else if(x3 < x1 && x0 > x1) { // two segments across x, down-left
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1);
stbtt__handle_clipped_edge(scanline, x, e, x1, y1, x3, y3);
}
else if(x0 < x2 && x3 > x2) { // two segments across x+1, down-right
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x2, y2);
stbtt__handle_clipped_edge(scanline, x, e, x2, y2, x3, y3);
}
else if(x3 < x2 && x0 > x2) { // two segments across x+1, down-left
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x2, y2);
stbtt__handle_clipped_edge(scanline, x, e, x2, y2, x3, y3);
}
else { // one segment
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x3, y3);
}
}
}
}
e = e->next;
}
}
// directly AA rasterize edges w/o supersampling
static void stbtt__rasterize_sorted_edges(stbtt__bitmap * result, stbtt__edge * e, int n, int vsubsample, int off_x,
int off_y, void * userdata)
{
stbtt__hheap hh = { 0, 0, 0 };
stbtt__active_edge * active = NULL;
int y, j = 0, i;
float scanline_data[129], * scanline, * scanline2;
STBTT__NOTUSED(vsubsample);
if(result->w > 64)
scanline = (float *)STBTT_malloc((result->w * 2 + 1) * sizeof(float), userdata);
else
scanline = scanline_data;
scanline2 = scanline + result->w;
y = off_y;
e[n].y0 = (float)(off_y + result->h) + 1;
while(j < result->h) {
// find center of pixel for this scanline
float scan_y_top = y + 0.0f;
float scan_y_bottom = y + 1.0f;
stbtt__active_edge ** step = &active;
STBTT_memset(scanline, 0, result->w * sizeof(scanline[0]));
STBTT_memset(scanline2, 0, (result->w + 1) * sizeof(scanline[0]));
// update all active edges;
// remove all active edges that terminate before the top of this scanline
while(*step) {
stbtt__active_edge * z = *step;
if(z->ey <= scan_y_top) {
*step = z->next; // delete from list
STBTT_assert(z->direction);
z->direction = 0;
stbtt__hheap_free(&hh, z);
}
else {
step = &((*step)->next); // advance through list
}
}
// insert all edges that start before the bottom of this scanline
while(e->y0 <= scan_y_bottom) {
if(e->y0 != e->y1) {
stbtt__active_edge * z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata);
if(z != NULL) {
if(j == 0 && off_y != 0) {
if(z->ey < scan_y_top) {
// this can happen due to subpixel positioning and some kind of fp rounding error i think
z->ey = scan_y_top;
}
}
STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds
// insert at front
z->next = active;
active = z;
}
}
++e;
}
// now process all active edges
if(active)
stbtt__fill_active_edges_new(scanline, scanline2 + 1, result->w, active, scan_y_top);
{
float sum = 0;
for(i = 0; i < result->w; ++i) {
float k;
int m;
sum += scanline2[i];
k = scanline[i] + sum;
k = (float)STBTT_fabs(k) * 255 + 0.5f;
m = (int)k;
if(m > 255) m = 255;
result->pixels[j * result->stride + i] = (unsigned char)m;
}
}
// advance all the edges
step = &active;
while(*step) {
stbtt__active_edge * z = *step;
z->fx += z->fdx; // advance to position for current scanline
step = &((*step)->next); // advance through list
}
++y;
++j;
}
stbtt__hheap_cleanup(&hh, userdata);
if(scanline != scanline_data)
STBTT_free(scanline, userdata);
}
#else
#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
#endif
#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0)
static void stbtt__sort_edges_ins_sort(stbtt__edge * p, int n)
{
int i, j;
for(i = 1; i < n; ++i) {
stbtt__edge t = p[i], * a = &t;
j = i;
while(j > 0) {
stbtt__edge * b = &p[j - 1];
int c = STBTT__COMPARE(a, b);
if(!c) break;
p[j] = p[j - 1];
--j;
}
if(i != j)
p[j] = t;
}
}
static void stbtt__sort_edges_quicksort(stbtt__edge * p, int n)
{
/* threshold for transitioning to insertion sort */
while(n > 12) {
stbtt__edge t;
int c01, c12, c, m, i, j;
/* compute median of three */
m = n >> 1;
c01 = STBTT__COMPARE(&p[0], &p[m]);
c12 = STBTT__COMPARE(&p[m], &p[n - 1]);
/* if 0 >= mid >= end, or 0 < mid < end, then use mid */
if(c01 != c12) {
/* otherwise, we'll need to swap something else to middle */
int z;
c = STBTT__COMPARE(&p[0], &p[n - 1]);
/* 0>mid && mid<n: 0>n => n; 0<n => 0 */
/* 0<mid && mid>n: 0>n => 0; 0<n => n */
z = (c == c12) ? 0 : n - 1;
t = p[z];
p[z] = p[m];
p[m] = t;
}
/* now p[m] is the median-of-three */
/* swap it to the beginning so it won't move around */
t = p[0];
p[0] = p[m];
p[m] = t;
/* partition loop */
i = 1;
j = n - 1;
for(;;) {
/* handling of equality is crucial here */
/* for sentinels & efficiency with duplicates */
for(;; ++i) {
if(!STBTT__COMPARE(&p[i], &p[0])) break;
}
for(;; --j) {
if(!STBTT__COMPARE(&p[0], &p[j])) break;
}
/* make sure we haven't crossed */
if(i >= j) break;
t = p[i];
p[i] = p[j];
p[j] = t;
++i;
--j;
}
/* recurse on smaller side, iterate on larger */
if(j < (n - i)) {
stbtt__sort_edges_quicksort(p, j);
p = p + i;
n = n - i;
}
else {
stbtt__sort_edges_quicksort(p + i, n - i);
n = j;
}
}
}
static void stbtt__sort_edges(stbtt__edge * p, int n)
{
stbtt__sort_edges_quicksort(p, n);
stbtt__sort_edges_ins_sort(p, n);
}
typedef struct {
float x, y;
} stbtt__point;
static void stbtt__rasterize(stbtt__bitmap * result, stbtt__point * pts, int * wcount, int windings, float scale_x,
float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void * userdata)
{
float y_scale_inv = invert ? -scale_y : scale_y;
stbtt__edge * e;
int n, i, j, k, m;
#if STBTT_RASTERIZER_VERSION == 1
int vsubsample = result->h < 8 ? 15 : 5;
#elif STBTT_RASTERIZER_VERSION == 2
int vsubsample = 1;
#else
#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
#endif
// vsubsample should divide 255 evenly; otherwise we won't reach full opacity
// now we have to blow out the windings into explicit edge lists
n = 0;
for(i = 0; i < windings; ++i)
n += wcount[i];
e = (stbtt__edge *)STBTT_malloc(sizeof(*e) * (n + 1), userdata); // add an extra one as a sentinel
if(e == 0) return;
n = 0;
m = 0;
for(i = 0; i < windings; ++i) {
stbtt__point * p = pts + m;
m += wcount[i];
j = wcount[i] - 1;
for(k = 0; k < wcount[i]; j = k++) {
int a = k, b = j;
// skip the edge if horizontal
if(p[j].y == p[k].y)
continue;
// add edge from j to k to the list
e[n].invert = 0;
if(invert ? p[j].y > p[k].y : p[j].y < p[k].y) {
e[n].invert = 1;
a = j, b = k;
}
e[n].x0 = p[a].x * scale_x + shift_x;
e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;
e[n].x1 = p[b].x * scale_x + shift_x;
e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;
++n;
}
}
// now sort the edges by their highest point (should snap to integer, and then by x)
//STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
stbtt__sort_edges(e, n);
// now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
STBTT_free(e, userdata);
}
static void stbtt__add_point(stbtt__point * points, int n, float x, float y)
{
if(!points) return; // during first pass, it's unallocated
points[n].x = x;
points[n].y = y;
}
// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching
static int stbtt__tesselate_curve(stbtt__point * points, int * num_points, float x0, float y0, float x1, float y1,
float x2, float y2, float objspace_flatness_squared, int n)
{
// midpoint
float mx = (x0 + 2 * x1 + x2) / 4;
float my = (y0 + 2 * y1 + y2) / 4;
// versus directly drawn line
float dx = (x0 + x2) / 2 - mx;
float dy = (y0 + y2) / 2 - my;
if(n > 16) // 65536 segments on one curve better be enough!
return 1;
if(dx * dx + dy * dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA
stbtt__tesselate_curve(points, num_points, x0, y0, (x0 + x1) / 2.0f, (y0 + y1) / 2.0f, mx, my,
objspace_flatness_squared, n + 1);
stbtt__tesselate_curve(points, num_points, mx, my, (x1 + x2) / 2.0f, (y1 + y2) / 2.0f, x2, y2,
objspace_flatness_squared, n + 1);
}
else {
stbtt__add_point(points, *num_points, x2, y2);
*num_points = *num_points + 1;
}
return 1;
}
static void stbtt__tesselate_cubic(stbtt__point * points, int * num_points, float x0, float y0, float x1, float y1,
float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n)
{
// @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough
float dx0 = x1 - x0;
float dy0 = y1 - y0;
float dx1 = x2 - x1;
float dy1 = y2 - y1;
float dx2 = x3 - x2;
float dy2 = y3 - y2;
float dx = x3 - x0;
float dy = y3 - y0;
float longlen = (float)(STBTT_sqrt(dx0 * dx0 + dy0 * dy0) + STBTT_sqrt(dx1 * dx1 + dy1 * dy1) + STBTT_sqrt(
dx2 * dx2 + dy2 * dy2));
float shortlen = (float)STBTT_sqrt(dx * dx + dy * dy);
float flatness_squared = longlen * longlen - shortlen * shortlen;
if(n > 16) // 65536 segments on one curve better be enough!
return;
if(flatness_squared > objspace_flatness_squared) {
float x01 = (x0 + x1) / 2;
float y01 = (y0 + y1) / 2;
float x12 = (x1 + x2) / 2;
float y12 = (y1 + y2) / 2;
float x23 = (x2 + x3) / 2;
float y23 = (y2 + y3) / 2;
float xa = (x01 + x12) / 2;
float ya = (y01 + y12) / 2;
float xb = (x12 + x23) / 2;
float yb = (y12 + y23) / 2;
float mx = (xa + xb) / 2;
float my = (ya + yb) / 2;
stbtt__tesselate_cubic(points, num_points, x0, y0, x01, y01, xa, ya, mx, my, objspace_flatness_squared, n + 1);
stbtt__tesselate_cubic(points, num_points, mx, my, xb, yb, x23, y23, x3, y3, objspace_flatness_squared, n + 1);
}
else {
stbtt__add_point(points, *num_points, x3, y3);
*num_points = *num_points + 1;
}
}
// returns number of contours
static stbtt__point * stbtt_FlattenCurves(stbtt_vertex * vertices, int num_verts, float objspace_flatness,
int ** contour_lengths, int * num_contours, void * userdata)
{
stbtt__point * points = 0;
int num_points = 0;
float objspace_flatness_squared = objspace_flatness * objspace_flatness;
int i, n = 0, start = 0, pass;
// count how many "moves" there are to get the contour count
for(i = 0; i < num_verts; ++i)
if(vertices[i].type == STBTT_vmove)
++n;
*num_contours = n;
if(n == 0) return 0;
*contour_lengths = (int *)STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
if(*contour_lengths == 0) {
*num_contours = 0;
return 0;
}
// make two passes through the points so we don't need to realloc
for(pass = 0; pass < 2; ++pass) {
float x = 0, y = 0;
if(pass == 1) {
points = (stbtt__point *)STBTT_malloc(num_points * sizeof(points[0]), userdata);
if(points == NULL) goto error;
}
num_points = 0;
n = -1;
for(i = 0; i < num_verts; ++i) {
switch(vertices[i].type) {
case STBTT_vmove:
// start the next contour
if(n >= 0)
(*contour_lengths)[n] = num_points - start;
++n;
start = num_points;
x = vertices[i].x, y = vertices[i].y;
stbtt__add_point(points, num_points++, x, y);
break;
case STBTT_vline:
x = vertices[i].x, y = vertices[i].y;
stbtt__add_point(points, num_points++, x, y);
break;
case STBTT_vcurve:
stbtt__tesselate_curve(points, &num_points, x, y,
vertices[i].cx, vertices[i].cy,
vertices[i].x, vertices[i].y,
objspace_flatness_squared, 0);
x = vertices[i].x, y = vertices[i].y;
break;
case STBTT_vcubic:
stbtt__tesselate_cubic(points, &num_points, x, y,
vertices[i].cx, vertices[i].cy,
vertices[i].cx1, vertices[i].cy1,
vertices[i].x, vertices[i].y,
objspace_flatness_squared, 0);
x = vertices[i].x, y = vertices[i].y;
break;
}
}
(*contour_lengths)[n] = num_points - start;
}
return points;
error:
STBTT_free(points, userdata);
STBTT_free(*contour_lengths, userdata);
*contour_lengths = 0;
*num_contours = 0;
return NULL;
}
STBTT_DEF void stbtt_Rasterize(stbtt__bitmap * result, float flatness_in_pixels, stbtt_vertex * vertices, int num_verts,
float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void * userdata)
{
float scale = scale_x > scale_y ? scale_y : scale_x;
int winding_count = 0;
int * winding_lengths = NULL;
stbtt__point * windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths,
&winding_count, userdata);
if(windings) {
stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off,
invert, userdata);
STBTT_free(winding_lengths, userdata);
STBTT_free(windings, userdata);
}
}
STBTT_DEF void stbtt_FreeBitmap(unsigned char * bitmap, void * userdata)
{
STBTT_free(bitmap, userdata);
}
STBTT_DEF unsigned char * stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo * info, float scale_x, float scale_y,
float shift_x, float shift_y, int glyph, int * width, int * height, int * xoff, int * yoff)
{
int ix0, iy0, ix1, iy1;
stbtt__bitmap gbm;
stbtt_vertex * vertices;
int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
if(scale_x == 0) scale_x = scale_y;
if(scale_y == 0) {
if(scale_x == 0) {
STBTT_free(vertices, info->userdata);
return NULL;
}
scale_y = scale_x;
}
stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0, &iy0, &ix1, &iy1);
// now we get the size
gbm.w = (ix1 - ix0);
gbm.h = (iy1 - iy0);
gbm.pixels = NULL; // in case we error
if(width) *width = gbm.w;
if(height) *height = gbm.h;
if(xoff) *xoff = ix0;
if(yoff) *yoff = iy0;
if(gbm.w && gbm.h) {
gbm.pixels = (unsigned char *)STBTT_malloc(gbm.w * gbm.h, info->userdata);
if(gbm.pixels) {
gbm.stride = gbm.w;
stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
}
}
STBTT_free(vertices, info->userdata);
return gbm.pixels;
}
STBTT_DEF unsigned char * stbtt_GetGlyphBitmap(const stbtt_fontinfo * info, float scale_x, float scale_y, int glyph,
int * width, int * height, int * xoff, int * yoff)
{
return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
}
STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo * info, unsigned char * output, int out_w, int out_h,
int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph)
{
int ix0, iy0;
stbtt_vertex * vertices;
int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
stbtt__bitmap gbm;
stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0, &iy0, 0, 0);
gbm.pixels = output;
gbm.w = out_w;
gbm.h = out_h;
gbm.stride = out_stride;
if(gbm.w && gbm.h)
stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
STBTT_free(vertices, info->userdata);
}
STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo * info, unsigned char * output, int out_w, int out_h,
int out_stride, float scale_x, float scale_y, int glyph)
{
stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f, 0.0f, glyph);
}
STBTT_DEF unsigned char * stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo * info, float scale_x, float scale_y,
float shift_x, float shift_y, int codepoint, int * width, int * height, int * xoff, int * yoff)
{
return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info, codepoint),
width, height, xoff, yoff);
}
STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo * info, unsigned char * output,
int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x,
int oversample_y, float * sub_x, float * sub_y, int codepoint)
{
stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y,
oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info, codepoint));
}
STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo * info, unsigned char * output, int out_w,
int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint)
{
stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y,
stbtt_FindGlyphIndex(info, codepoint));
}
STBTT_DEF unsigned char * stbtt_GetCodepointBitmap(const stbtt_fontinfo * info, float scale_x, float scale_y,
int codepoint, int * width, int * height, int * xoff, int * yoff)
{
return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, codepoint, width, height, xoff, yoff);
}
STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo * info, unsigned char * output, int out_w, int out_h,
int out_stride, float scale_x, float scale_y, int codepoint)
{
stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f, 0.0f, codepoint);
}
//////////////////////////////////////////////////////////////////////////////
//
// bitmap baking
//
// This is SUPER-CRAPPY packing to keep source code small
#ifdef STBTT_STREAM_TYPE
static int stbtt_BakeFontBitmap_internal(STBTT_STREAM_TYPE data,
int offset, // font location (use offset=0 for plain .ttf)
float pixel_height, // height of font in pixels
unsigned char * pixels, int pw, int ph, // bitmap to be filled in
int first_char, int num_chars, // characters to bake
stbtt_bakedchar * chardata)
#else
static int stbtt_BakeFontBitmap_internal(unsigned char * data,
int offset, // font location (use offset=0 for plain .ttf)
float pixel_height, // height of font in pixels
unsigned char * pixels, int pw, int ph, // bitmap to be filled in
int first_char, int num_chars, // characters to bake
stbtt_bakedchar * chardata)
#endif
{
float scale;
int x, y, bottom_y, i;
stbtt_fontinfo f;
f.userdata = NULL;
if(!stbtt_InitFont(&f, data, offset))
return -1;
STBTT_memset(pixels, 0, pw * ph); // background of 0 around pixels
x = y = 1;
bottom_y = 1;
scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
for(i = 0; i < num_chars; ++i) {
int advance, lsb, x0, y0, x1, y1, gw, gh;
int g = stbtt_FindGlyphIndex(&f, first_char + i);
stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
stbtt_GetGlyphBitmapBox(&f, g, scale, scale, &x0, &y0, &x1, &y1);
gw = x1 - x0;
gh = y1 - y0;
if(x + gw + 1 >= pw)
y = bottom_y, x = 1; // advance to next row
if(y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row
return -i;
STBTT_assert(x + gw < pw);
STBTT_assert(y + gh < ph);
stbtt_MakeGlyphBitmap(&f, pixels + x + y * pw, gw, gh, pw, scale, scale, g);
chardata[i].x0 = (stbtt_int16)x;
chardata[i].y0 = (stbtt_int16)y;
chardata[i].x1 = (stbtt_int16)(x + gw);
chardata[i].y1 = (stbtt_int16)(y + gh);
chardata[i].xadvance = scale * advance;
chardata[i].xoff = (float)x0;
chardata[i].yoff = (float)y0;
x = x + gw + 1;
if(y + gh + 1 > bottom_y)
bottom_y = y + gh + 1;
}
return bottom_y;
}
STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar * chardata, int pw, int ph, int char_index, float * xpos,
float * ypos, stbtt_aligned_quad * q, int opengl_fillrule)
{
float d3d_bias = opengl_fillrule ? 0 : -0.5f;
float ipw = 1.0f / pw, iph = 1.0f / ph;
const stbtt_bakedchar * b = chardata + char_index;
int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);
int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);
q->x0 = round_x + d3d_bias;
q->y0 = round_y + d3d_bias;
q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
q->s0 = b->x0 * ipw;
q->t0 = b->y0 * iph;
q->s1 = b->x1 * ipw;
q->t1 = b->y1 * iph;
*xpos += b->xadvance;
}
//////////////////////////////////////////////////////////////////////////////
//
// rectangle packing replacement routines if you don't have stb_rect_pack.h
//
#ifndef STB_RECT_PACK_VERSION
typedef int stbrp_coord;
////////////////////////////////////////////////////////////////////////////////////
// //
// //
// COMPILER WARNING ?!?!? //
// //
// //
// if you get a compile warning due to these symbols being defined more than //
// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" //
// //
////////////////////////////////////////////////////////////////////////////////////
typedef struct {
int width, height;
int x, y, bottom_y;
} stbrp_context;
typedef struct {
unsigned char x;
} stbrp_node;
struct stbrp_rect {
stbrp_coord x, y;
int id, w, h, was_packed;
};
static void stbrp_init_target(stbrp_context * con, int pw, int ph, stbrp_node * nodes, int num_nodes)
{
con->width = pw;
con->height = ph;
con->x = 0;
con->y = 0;
con->bottom_y = 0;
STBTT__NOTUSED(nodes);
STBTT__NOTUSED(num_nodes);
}
static void stbrp_pack_rects(stbrp_context * con, stbrp_rect * rects, int num_rects)
{
int i;
for(i = 0; i < num_rects; ++i) {
if(con->x + rects[i].w > con->width) {
con->x = 0;
con->y = con->bottom_y;
}
if(con->y + rects[i].h > con->height)
break;
rects[i].x = con->x;
rects[i].y = con->y;
rects[i].was_packed = 1;
con->x += rects[i].w;
if(con->y + rects[i].h > con->bottom_y)
con->bottom_y = con->y + rects[i].h;
}
for(; i < num_rects; ++i)
rects[i].was_packed = 0;
}
#endif
//////////////////////////////////////////////////////////////////////////////
//
// bitmap baking
//
// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If
// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.
STBTT_DEF int stbtt_PackBegin(stbtt_pack_context * spc, unsigned char * pixels, int pw, int ph, int stride_in_bytes,
int padding, void * alloc_context)
{
stbrp_context * context = (stbrp_context *)STBTT_malloc(sizeof(*context), alloc_context);
int num_nodes = pw - padding;
stbrp_node * nodes = (stbrp_node *)STBTT_malloc(sizeof(*nodes) * num_nodes, alloc_context);
if(context == NULL || nodes == NULL) {
if(context != NULL) STBTT_free(context, alloc_context);
if(nodes != NULL) STBTT_free(nodes, alloc_context);
return 0;
}
spc->user_allocator_context = alloc_context;
spc->width = pw;
spc->height = ph;
spc->pixels = pixels;
spc->pack_info = context;
spc->nodes = nodes;
spc->padding = padding;
spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;
spc->h_oversample = 1;
spc->v_oversample = 1;
spc->skip_missing = 0;
stbrp_init_target(context, pw - padding, ph - padding, nodes, num_nodes);
if(pixels)
STBTT_memset(pixels, 0, pw * ph); // background of 0 around pixels
return 1;
}
STBTT_DEF void stbtt_PackEnd(stbtt_pack_context * spc)
{
STBTT_free(spc->nodes, spc->user_allocator_context);
STBTT_free(spc->pack_info, spc->user_allocator_context);
}
STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context * spc, unsigned int h_oversample, unsigned int v_oversample)
{
STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);
STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);
if(h_oversample <= STBTT_MAX_OVERSAMPLE)
spc->h_oversample = h_oversample;
if(v_oversample <= STBTT_MAX_OVERSAMPLE)
spc->v_oversample = v_oversample;
}
STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context * spc, int skip)
{
spc->skip_missing = skip;
}
#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1)
static void stbtt__h_prefilter(unsigned char * pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
{
unsigned char buffer[STBTT_MAX_OVERSAMPLE];
int safe_w = w - kernel_width;
int j;
STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
for(j = 0; j < h; ++j) {
int i;
unsigned int total;
STBTT_memset(buffer, 0, kernel_width);
total = 0;
// make kernel_width a constant in common cases so compiler can optimize out the divide
switch(kernel_width) {
case 2:
for(i = 0; i <= safe_w; ++i) {
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char)(total / 2);
}
break;
case 3:
for(i = 0; i <= safe_w; ++i) {
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char)(total / 3);
}
break;
case 4:
for(i = 0; i <= safe_w; ++i) {
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char)(total / 4);
}
break;
case 5:
for(i = 0; i <= safe_w; ++i) {
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char)(total / 5);
}
break;
default:
for(i = 0; i <= safe_w; ++i) {
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char)(total / kernel_width);
}
break;
}
for(; i < w; ++i) {
STBTT_assert(pixels[i] == 0);
total -= buffer[i & STBTT__OVER_MASK];
pixels[i] = (unsigned char)(total / kernel_width);
}
pixels += stride_in_bytes;
}
}
static void stbtt__v_prefilter(unsigned char * pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
{
unsigned char buffer[STBTT_MAX_OVERSAMPLE];
int safe_h = h - kernel_width;
int j;
STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
for(j = 0; j < w; ++j) {
int i;
unsigned int total;
STBTT_memset(buffer, 0, kernel_width);
total = 0;
// make kernel_width a constant in common cases so compiler can optimize out the divide
switch(kernel_width) {
case 2:
for(i = 0; i <= safe_h; ++i) {
total += pixels[i * stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i * stride_in_bytes];
pixels[i * stride_in_bytes] = (unsigned char)(total / 2);
}
break;
case 3:
for(i = 0; i <= safe_h; ++i) {
total += pixels[i * stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i * stride_in_bytes];
pixels[i * stride_in_bytes] = (unsigned char)(total / 3);
}
break;
case 4:
for(i = 0; i <= safe_h; ++i) {
total += pixels[i * stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i * stride_in_bytes];
pixels[i * stride_in_bytes] = (unsigned char)(total / 4);
}
break;
case 5:
for(i = 0; i <= safe_h; ++i) {
total += pixels[i * stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i * stride_in_bytes];
pixels[i * stride_in_bytes] = (unsigned char)(total / 5);
}
break;
default:
for(i = 0; i <= safe_h; ++i) {
total += pixels[i * stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i * stride_in_bytes];
pixels[i * stride_in_bytes] = (unsigned char)(total / kernel_width);
}
break;
}
for(; i < h; ++i) {
STBTT_assert(pixels[i * stride_in_bytes] == 0);
total -= buffer[i & STBTT__OVER_MASK];
pixels[i * stride_in_bytes] = (unsigned char)(total / kernel_width);
}
pixels += 1;
}
}
static float stbtt__oversample_shift(int oversample)
{
if(!oversample)
return 0.0f;
// The prefilter is a box filter of width "oversample",
// which shifts phase by (oversample - 1)/2 pixels in
// oversampled space. We want to shift in the opposite
// direction to counter this.
return (float) - (oversample - 1) / (2.0f * (float)oversample);
}
// rects array must be big enough to accommodate all characters in the given ranges
STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context * spc, const stbtt_fontinfo * info,
stbtt_pack_range * ranges, int num_ranges, stbrp_rect * rects)
{
int i, j, k;
int missing_glyph_added = 0;
k = 0;
for(i = 0; i < num_ranges; ++i) {
float fh = ranges[i].font_size;
float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
ranges[i].h_oversample = (unsigned char)spc->h_oversample;
ranges[i].v_oversample = (unsigned char)spc->v_oversample;
for(j = 0; j < ranges[i].num_chars; ++j) {
int x0, y0, x1, y1;
int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j :
ranges[i].array_of_unicode_codepoints[j];
int glyph = stbtt_FindGlyphIndex(info, codepoint);
if(glyph == 0 && (spc->skip_missing || missing_glyph_added)) {
rects[k].w = rects[k].h = 0;
}
else {
stbtt_GetGlyphBitmapBoxSubpixel(info, glyph,
scale * spc->h_oversample,
scale * spc->v_oversample,
0, 0,
&x0, &y0, &x1, &y1);
rects[k].w = (stbrp_coord)(x1 - x0 + spc->padding + spc->h_oversample - 1);
rects[k].h = (stbrp_coord)(y1 - y0 + spc->padding + spc->v_oversample - 1);
if(glyph == 0)
missing_glyph_added = 1;
}
++k;
}
}
return k;
}
STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo * info, unsigned char * output, int out_w,
int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y,
float * sub_x, float * sub_y, int glyph)
{
stbtt_MakeGlyphBitmapSubpixel(info,
output,
out_w - (prefilter_x - 1),
out_h - (prefilter_y - 1),
out_stride,
scale_x,
scale_y,
shift_x,
shift_y,
glyph);
if(prefilter_x > 1)
stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x);
if(prefilter_y > 1)
stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y);
*sub_x = stbtt__oversample_shift(prefilter_x);
*sub_y = stbtt__oversample_shift(prefilter_y);
}
// rects array must be big enough to accommodate all characters in the given ranges
STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context * spc, const stbtt_fontinfo * info,
stbtt_pack_range * ranges, int num_ranges, stbrp_rect * rects)
{
int i, j, k, missing_glyph = -1, return_value = 1;
// save current values
int old_h_over = spc->h_oversample;
int old_v_over = spc->v_oversample;
k = 0;
for(i = 0; i < num_ranges; ++i) {
float fh = ranges[i].font_size;
float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
float recip_h, recip_v, sub_x, sub_y;
spc->h_oversample = ranges[i].h_oversample;
spc->v_oversample = ranges[i].v_oversample;
recip_h = 1.0f / spc->h_oversample;
recip_v = 1.0f / spc->v_oversample;
sub_x = stbtt__oversample_shift(spc->h_oversample);
sub_y = stbtt__oversample_shift(spc->v_oversample);
for(j = 0; j < ranges[i].num_chars; ++j) {
stbrp_rect * r = &rects[k];
if(r->was_packed && r->w != 0 && r->h != 0) {
stbtt_packedchar * bc = &ranges[i].chardata_for_range[j];
int advance, lsb, x0, y0, x1, y1;
int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j :
ranges[i].array_of_unicode_codepoints[j];
int glyph = stbtt_FindGlyphIndex(info, codepoint);
stbrp_coord pad = (stbrp_coord)spc->padding;
// pad on left and top
r->x += pad;
r->y += pad;
r->w -= pad;
r->h -= pad;
stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);
stbtt_GetGlyphBitmapBox(info, glyph,
scale * spc->h_oversample,
scale * spc->v_oversample,
&x0, &y0, &x1, &y1);
stbtt_MakeGlyphBitmapSubpixel(info,
spc->pixels + r->x + r->y * spc->stride_in_bytes,
r->w - spc->h_oversample + 1,
r->h - spc->v_oversample + 1,
spc->stride_in_bytes,
scale * spc->h_oversample,
scale * spc->v_oversample,
0, 0,
glyph);
if(spc->h_oversample > 1)
stbtt__h_prefilter(spc->pixels + r->x + r->y * spc->stride_in_bytes,
r->w, r->h, spc->stride_in_bytes,
spc->h_oversample);
if(spc->v_oversample > 1)
stbtt__v_prefilter(spc->pixels + r->x + r->y * spc->stride_in_bytes,
r->w, r->h, spc->stride_in_bytes,
spc->v_oversample);
bc->x0 = (stbtt_int16)r->x;
bc->y0 = (stbtt_int16)r->y;
bc->x1 = (stbtt_int16)(r->x + r->w);
bc->y1 = (stbtt_int16)(r->y + r->h);
bc->xadvance = scale * advance;
bc->xoff = (float)x0 * recip_h + sub_x;
bc->yoff = (float)y0 * recip_v + sub_y;
bc->xoff2 = (x0 + r->w) * recip_h + sub_x;
bc->yoff2 = (y0 + r->h) * recip_v + sub_y;
if(glyph == 0)
missing_glyph = j;
}
else if(spc->skip_missing) {
return_value = 0;
}
else if(r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) {
ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph];
}
else {
return_value = 0; // if any fail, report failure
}
++k;
}
}
// restore original values
spc->h_oversample = old_h_over;
spc->v_oversample = old_v_over;
return return_value;
}
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context * spc, STBTT_STREAM_TYPE fontdata, int font_index,
stbtt_pack_range * ranges, int num_ranges);
#else
STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context * spc, const unsigned char * fontdata, int font_index,
stbtt_pack_range * ranges, int num_ranges);
#endif
STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context * spc, stbrp_rect * rects, int num_rects)
{
stbrp_pack_rects((stbrp_context *)spc->pack_info, rects, num_rects);
}
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context * spc, STBTT_STREAM_TYPE fontdata, int font_index,
stbtt_pack_range * ranges, int num_ranges)
#else
STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context * spc, const unsigned char * fontdata, int font_index,
stbtt_pack_range * ranges, int num_ranges)
#endif
{
stbtt_fontinfo info;
int i, j, n, return_value = 1;
//stbrp_context *context = (stbrp_context *) spc->pack_info;
stbrp_rect * rects;
// flag all characters as NOT packed
for(i = 0; i < num_ranges; ++i)
for(j = 0; j < ranges[i].num_chars; ++j)
ranges[i].chardata_for_range[j].x0 =
ranges[i].chardata_for_range[j].y0 =
ranges[i].chardata_for_range[j].x1 =
ranges[i].chardata_for_range[j].y1 = 0;
n = 0;
for(i = 0; i < num_ranges; ++i)
n += ranges[i].num_chars;
rects = (stbrp_rect *)STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);
if(rects == NULL)
return 0;
info.userdata = spc->user_allocator_context;
stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, font_index));
n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects);
stbtt_PackFontRangesPackRects(spc, rects, n);
return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects);
STBTT_free(rects, spc->user_allocator_context);
return return_value;
}
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context * spc, STBTT_STREAM_TYPE fontdata, int font_index, float font_size,
int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar * chardata_for_range);
#else
STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context * spc, const unsigned char * fontdata, int font_index,
float font_size,
int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar * chardata_for_range);
#endif
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context * spc, STBTT_STREAM_TYPE fontdata, int font_index, float font_size,
int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar * chardata_for_range)
#else
STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context * spc, const unsigned char * fontdata, int font_index,
float font_size,
int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar * chardata_for_range)
#endif
{
stbtt_pack_range range;
range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range;
range.array_of_unicode_codepoints = NULL;
range.num_chars = num_chars_in_range;
range.chardata_for_range = chardata_for_range;
range.font_size = font_size;
return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);
}
#ifdef STBTT_STREAM_TYPE
STBTT_DEF void stbtt_GetScaledFontVMetrics(STBTT_STREAM_TYPE fontdata, int index, float size, float * ascent,
float * descent, float * lineGap);
#else
STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char * fontdata, int index, float size, float * ascent,
float * descent, float * lineGap);
#endif
#ifdef STBTT_STREAM_TYPE
STBTT_DEF void stbtt_GetScaledFontVMetrics(STBTT_STREAM_TYPE fontdata, int index, float size, float * ascent,
float * descent, float * lineGap)
#else
STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char * fontdata, int index, float size, float * ascent,
float * descent, float * lineGap)
#endif
{
int i_ascent, i_descent, i_lineGap;
float scale;
stbtt_fontinfo info;
stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index));
scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size);
stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap);
*ascent = (float)i_ascent * scale;
*descent = (float)i_descent * scale;
*lineGap = (float)i_lineGap * scale;
}
STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar * chardata, int pw, int ph, int char_index, float * xpos,
float * ypos, stbtt_aligned_quad * q, int align_to_integer)
{
float ipw = 1.0f / pw, iph = 1.0f / ph;
const stbtt_packedchar * b = chardata + char_index;
if(align_to_integer) {
float x = (float)STBTT_ifloor((*xpos + b->xoff) + 0.5f);
float y = (float)STBTT_ifloor((*ypos + b->yoff) + 0.5f);
q->x0 = x;
q->y0 = y;
q->x1 = x + b->xoff2 - b->xoff;
q->y1 = y + b->yoff2 - b->yoff;
}
else {
q->x0 = *xpos + b->xoff;
q->y0 = *ypos + b->yoff;
q->x1 = *xpos + b->xoff2;
q->y1 = *ypos + b->yoff2;
}
q->s0 = b->x0 * ipw;
q->t0 = b->y0 * iph;
q->s1 = b->x1 * ipw;
q->t1 = b->y1 * iph;
*xpos += b->xadvance;
}
//////////////////////////////////////////////////////////////////////////////
//
// sdf computation
//
#define STBTT_min(a,b) ((a) < (b) ? (a) : (b))
#define STBTT_max(a,b) ((a) < (b) ? (b) : (a))
static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2],
float hits[2][2])
{
float q0perp = q0[1] * ray[0] - q0[0] * ray[1];
float q1perp = q1[1] * ray[0] - q1[0] * ray[1];
float q2perp = q2[1] * ray[0] - q2[0] * ray[1];
float roperp = orig[1] * ray[0] - orig[0] * ray[1];
float a = q0perp - 2 * q1perp + q2perp;
float b = q1perp - q0perp;
float c = q0perp - roperp;
float s0 = 0., s1 = 0.;
int num_s = 0;
if(a != 0.0f) {
float discr = b * b - a * c;
if(discr > 0.0f) {
float rcpna = -1 / a;
float d = (float)STBTT_sqrt(discr);
s0 = (b + d) * rcpna;
s1 = (b - d) * rcpna;
if(s0 >= 0.0f && s0 <= 1.0f)
num_s = 1;
if(d > 0.0f && s1 >= 0.0f && s1 <= 1.0f) {
if(num_s == 0) s0 = s1;
++num_s;
}
}
}
else {
// 2*b*s + c = 0
// s = -c / (2*b)
s0 = c / (-2 * b);
if(s0 >= 0.0f && s0 <= 1.0f)
num_s = 1;
}
if(num_s == 0)
return 0;
else {
float rcp_len2 = 1 / (ray[0] * ray[0] + ray[1] * ray[1]);
float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2;
float q0d = q0[0] * rayn_x + q0[1] * rayn_y;
float q1d = q1[0] * rayn_x + q1[1] * rayn_y;
float q2d = q2[0] * rayn_x + q2[1] * rayn_y;
float rod = orig[0] * rayn_x + orig[1] * rayn_y;
float q10d = q1d - q0d;
float q20d = q2d - q0d;
float q0rd = q0d - rod;
hits[0][0] = q0rd + s0 * (2.0f - 2.0f * s0) * q10d + s0 * s0 * q20d;
hits[0][1] = a * s0 + b;
if(num_s > 1) {
hits[1][0] = q0rd + s1 * (2.0f - 2.0f * s1) * q10d + s1 * s1 * q20d;
hits[1][1] = a * s1 + b;
return 2;
}
else {
return 1;
}
}
}
static int equal(float * a, float * b)
{
return (a[0] == b[0] && a[1] == b[1]);
}
static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex * verts)
{
int i;
float orig[2], ray[2] = { 1, 0 };
float y_frac;
int winding = 0;
// make sure y never passes through a vertex of the shape
y_frac = (float)STBTT_fmod(y, 1.0f);
if(y_frac < 0.01f)
y += 0.01f;
else if(y_frac > 0.99f)
y -= 0.01f;
orig[0] = x;
orig[1] = y;
// test a ray from (-infinity,y) to (x,y)
for(i = 0; i < nverts; ++i) {
if(verts[i].type == STBTT_vline) {
int x0 = (int)verts[i - 1].x, y0 = (int)verts[i - 1].y;
int x1 = (int)verts[i].x, y1 = (int)verts[i].y;
if(y > STBTT_min(y0, y1) && y < STBTT_max(y0, y1) && x > STBTT_min(x0, x1)) {
float x_inter = (y - y0) / (y1 - y0) * (x1 - x0) + x0;
if(x_inter < x)
winding += (y0 < y1) ? 1 : -1;
}
}
if(verts[i].type == STBTT_vcurve) {
int x0 = (int)verts[i - 1].x, y0 = (int)verts[i - 1].y;
int x1 = (int)verts[i].cx, y1 = (int)verts[i].cy;
int x2 = (int)verts[i].x, y2 = (int)verts[i].y;
int ax = STBTT_min(x0, STBTT_min(x1, x2)), ay = STBTT_min(y0, STBTT_min(y1, y2));
int by = STBTT_max(y0, STBTT_max(y1, y2));
if(y > ay && y < by && x > ax) {
float q0[2], q1[2], q2[2];
float hits[2][2];
q0[0] = (float)x0;
q0[1] = (float)y0;
q1[0] = (float)x1;
q1[1] = (float)y1;
q2[0] = (float)x2;
q2[1] = (float)y2;
if(equal(q0, q1) || equal(q1, q2)) {
x0 = (int)verts[i - 1].x;
y0 = (int)verts[i - 1].y;
x1 = (int)verts[i].x;
y1 = (int)verts[i].y;
if(y > STBTT_min(y0, y1) && y < STBTT_max(y0, y1) && x > STBTT_min(x0, x1)) {
float x_inter = (y - y0) / (y1 - y0) * (x1 - x0) + x0;
if(x_inter < x)
winding += (y0 < y1) ? 1 : -1;
}
}
else {
int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits);
if(num_hits >= 1)
if(hits[0][0] < 0)
winding += (hits[0][1] < 0 ? -1 : 1);
if(num_hits >= 2)
if(hits[1][0] < 0)
winding += (hits[1][1] < 0 ? -1 : 1);
}
}
}
}
return winding;
}
static float stbtt__cuberoot(float x)
{
if(x < 0)
return -(float)STBTT_pow(-x, 1.0f / 3.0f);
else
return (float)STBTT_pow(x, 1.0f / 3.0f);
}
// x^3 + a*x^2 + b*x + c = 0
static int stbtt__solve_cubic(float a, float b, float c, float * r)
{
float s = -a / 3;
float p = b - a * a / 3;
float q = a * (2 * a * a - 9 * b) / 27 + c;
float p3 = p * p * p;
float d = q * q + 4 * p3 / 27;
if(d >= 0) {
float z = (float)STBTT_sqrt(d);
float u = (-q + z) / 2;
float v = (-q - z) / 2;
u = stbtt__cuberoot(u);
v = stbtt__cuberoot(v);
r[0] = s + u + v;
return 1;
}
else {
float u = (float)STBTT_sqrt(-p / 3);
float v = (float)STBTT_acos(-STBTT_sqrt(-27 / p3) * q / 2) / 3; // p3 must be negative, since d is negative
float m = (float)STBTT_cos(v);
float n = (float)STBTT_cos(v - 3.141592f / 2) * 1.732050808f;
r[0] = s + u * 2 * m;
r[1] = s - u * (m + n);
r[2] = s - u * (m - n);
//STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe?
//STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f);
//STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f);
return 3;
}
}
STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo * info, float scale, int glyph, int padding,
unsigned char onedge_value, float pixel_dist_scale, int * width, int * height, int * xoff, int * yoff)
{
float scale_x = scale, scale_y = scale;
int ix0, iy0, ix1, iy1;
int w, h;
unsigned char * data;
if(scale == 0) return NULL;
stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f, 0.0f, &ix0, &iy0, &ix1, &iy1);
// if empty, return NULL
if(ix0 == ix1 || iy0 == iy1)
return NULL;
ix0 -= padding;
iy0 -= padding;
ix1 += padding;
iy1 += padding;
w = (ix1 - ix0);
h = (iy1 - iy0);
if(width) *width = w;
if(height) *height = h;
if(xoff) *xoff = ix0;
if(yoff) *yoff = iy0;
// invert for y-downwards bitmaps
scale_y = -scale_y;
{
int x, y, i, j;
float * precompute;
stbtt_vertex * verts;
int num_verts = stbtt_GetGlyphShape(info, glyph, &verts);
data = (unsigned char *)STBTT_malloc(w * h, info->userdata);
precompute = (float *)STBTT_malloc(num_verts * sizeof(float), info->userdata);
for(i = 0, j = num_verts - 1; i < num_verts; j = i++) {
if(verts[i].type == STBTT_vline) {
float x0 = verts[i].x * scale_x, y0 = verts[i].y * scale_y;
float x1 = verts[j].x * scale_x, y1 = verts[j].y * scale_y;
float dist = (float)STBTT_sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));
precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist;
}
else if(verts[i].type == STBTT_vcurve) {
float x2 = verts[j].x * scale_x, y2 = verts[j].y * scale_y;
float x1 = verts[i].cx * scale_x, y1 = verts[i].cy * scale_y;
float x0 = verts[i].x * scale_x, y0 = verts[i].y * scale_y;
float bx = x0 - 2 * x1 + x2, by = y0 - 2 * y1 + y2;
float len2 = bx * bx + by * by;
if(len2 != 0.0f)
precompute[i] = 1.0f / (bx * bx + by * by);
else
precompute[i] = 0.0f;
}
else
precompute[i] = 0.0f;
}
for(y = iy0; y < iy1; ++y) {
for(x = ix0; x < ix1; ++x) {
float val;
float min_dist = 999999.0f;
float sx = (float)x + 0.5f;
float sy = (float)y + 0.5f;
float x_gspace = (sx / scale_x);
float y_gspace = (sy / scale_y);
int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts,
verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path
for(i = 0; i < num_verts; ++i) {
float x0 = verts[i].x * scale_x, y0 = verts[i].y * scale_y;
if(verts[i].type == STBTT_vline && precompute[i] != 0.0f) {
float x1 = verts[i - 1].x * scale_x, y1 = verts[i - 1].y * scale_y;
float dist, dist2 = (x0 - sx) * (x0 - sx) + (y0 - sy) * (y0 - sy);
if(dist2 < min_dist * min_dist)
min_dist = (float)STBTT_sqrt(dist2);
// coarse culling against bbox
//if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist &&
// sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist)
dist = (float)STBTT_fabs((x1 - x0) * (y0 - sy) - (y1 - y0) * (x0 - sx)) * precompute[i];
STBTT_assert(i != 0);
if(dist < min_dist) {
// check position along line
// x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0)
// minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy)
float dx = x1 - x0, dy = y1 - y0;
float px = x0 - sx, py = y0 - sy;
// minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy
// derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve
float t = -(px * dx + py * dy) / (dx * dx + dy * dy);
if(t >= 0.0f && t <= 1.0f)
min_dist = dist;
}
}
else if(verts[i].type == STBTT_vcurve) {
float x2 = verts[i - 1].x * scale_x, y2 = verts[i - 1].y * scale_y;
float x1 = verts[i].cx * scale_x, y1 = verts[i].cy * scale_y;
float box_x0 = STBTT_min(STBTT_min(x0, x1), x2);
float box_y0 = STBTT_min(STBTT_min(y0, y1), y2);
float box_x1 = STBTT_max(STBTT_max(x0, x1), x2);
float box_y1 = STBTT_max(STBTT_max(y0, y1), y2);
// coarse culling against bbox to avoid computing cubic unnecessarily
if(sx > box_x0 - min_dist && sx < box_x1 + min_dist && sy > box_y0 - min_dist && sy < box_y1 + min_dist) {
int num = 0;
float ax = x1 - x0, ay = y1 - y0;
float bx = x0 - 2 * x1 + x2, by = y0 - 2 * y1 + y2;
float mx = x0 - sx, my = y0 - sy;
float res[3] = { 0.f, 0.f, 0.f };
float px, py, t, it, dist2;
float a_inv = precompute[i];
if(a_inv == 0.0f) { // if a_inv is 0, it's 2nd degree so use quadratic formula
float a = 3 * (ax * bx + ay * by);
float b = 2 * (ax * ax + ay * ay) + (mx * bx + my * by);
float c = mx * ax + my * ay;
if(a == 0.0f) { // if a is 0, it's linear
if(b != 0.0f) {
res[num++] = -c / b;
}
}
else {
float discriminant = b * b - 4 * a * c;
if(discriminant < 0)
num = 0;
else {
float root = (float)STBTT_sqrt(discriminant);
res[0] = (-b - root) / (2 * a);
res[1] = (-b + root) / (2 * a);
num = 2; // don't bother distinguishing 1-solution case, as code below will still work
}
}
}
else {
float b = 3 * (ax * bx + ay * by) * a_inv; // could precompute this as it doesn't depend on sample point
float c = (2 * (ax * ax + ay * ay) + (mx * bx + my * by)) * a_inv;
float d = (mx * ax + my * ay) * a_inv;
num = stbtt__solve_cubic(b, c, d, res);
}
dist2 = (x0 - sx) * (x0 - sx) + (y0 - sy) * (y0 - sy);
if(dist2 < min_dist * min_dist)
min_dist = (float)STBTT_sqrt(dist2);
if(num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) {
t = res[0], it = 1.0f - t;
px = it * it * x0 + 2 * t * it * x1 + t * t * x2;
py = it * it * y0 + 2 * t * it * y1 + t * t * y2;
dist2 = (px - sx) * (px - sx) + (py - sy) * (py - sy);
if(dist2 < min_dist * min_dist)
min_dist = (float)STBTT_sqrt(dist2);
}
if(num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) {
t = res[1], it = 1.0f - t;
px = it * it * x0 + 2 * t * it * x1 + t * t * x2;
py = it * it * y0 + 2 * t * it * y1 + t * t * y2;
dist2 = (px - sx) * (px - sx) + (py - sy) * (py - sy);
if(dist2 < min_dist * min_dist)
min_dist = (float)STBTT_sqrt(dist2);
}
if(num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) {
t = res[2], it = 1.0f - t;
px = it * it * x0 + 2 * t * it * x1 + t * t * x2;
py = it * it * y0 + 2 * t * it * y1 + t * t * y2;
dist2 = (px - sx) * (px - sx) + (py - sy) * (py - sy);
if(dist2 < min_dist * min_dist)
min_dist = (float)STBTT_sqrt(dist2);
}
}
}
}
if(winding == 0)
min_dist = -min_dist; // if outside the shape, value is negative
val = onedge_value + pixel_dist_scale * min_dist;
if(val < 0)
val = 0;
else if(val > 255)
val = 255;
data[(y - iy0) * w + (x - ix0)] = (unsigned char)val;
}
}
STBTT_free(precompute, info->userdata);
STBTT_free(verts, info->userdata);
}
return data;
}
STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo * info, float scale, int codepoint, int padding,
unsigned char onedge_value, float pixel_dist_scale, int * width, int * height, int * xoff, int * yoff)
{
return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale,
width, height, xoff, yoff);
}
STBTT_DEF void stbtt_FreeSDF(unsigned char * bitmap, void * userdata)
{
STBTT_free(bitmap, userdata);
}
//////////////////////////////////////////////////////////////////////////////
//
// font name matching -- recommended not to use this
//
// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
#ifdef STBTT_STREAM_TYPE
static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 * s1, stbtt_int32 len1, STBTT_STREAM_TYPE s2,
stbtt_uint32 s2offs, stbtt_int32 len2)
#else
static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 * s1, stbtt_int32 len1, stbtt_uint8 * s2,
stbtt_uint32 s2offs, stbtt_int32 len2)
#endif
{
stbtt_int32 i = 0;
// convert utf16 to utf8 and compare the results while converting
while(len2) {
stbtt_uint16 ch = ttUSHORT(s2, s2offs);
if(ch < 0x80) {
if(i >= len1) return -1;
if(s1[i++] != ch) return -1;
}
else if(ch < 0x800) {
if(i + 1 >= len1) return -1;
if(s1[i++] != 0xc0 + (ch >> 6)) return -1;
if(s1[i++] != 0x80 + (ch & 0x3f)) return -1;
}
else if(ch >= 0xd800 && ch < 0xdc00) {
stbtt_uint32 c;
stbtt_uint16 ch2 = ttUSHORT(s2, s2offs + 2);
if(i + 3 >= len1) return -1;
c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
if(s1[i++] != 0xf0 + (c >> 18)) return -1;
if(s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;
if(s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1;
if(s1[i++] != 0x80 + ((c) & 0x3f)) return -1;
s2offs += 2; // plus another 2 below
len2 -= 2;
}
else if(ch >= 0xdc00 && ch < 0xe000) {
return -1;
}
else {
if(i + 2 >= len1) return -1;
if(s1[i++] != 0xe0 + (ch >> 12)) return -1;
if(s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;
if(s1[i++] != 0x80 + ((ch) & 0x3f)) return -1;
}
s2offs += 2;
len2 -= 2;
}
return i;
}
#ifdef STBTT_STREAM_TYPE
static int stbtt_CompareUTF8toUTF16_bigendian_internal(char * s1, int len1, STBTT_STREAM_TYPE s2, stbtt_uint32 s2offs,
int len2)
{
return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8 *)s1, len1, s2, s2offs, len2);
}
#else
static int stbtt_CompareUTF8toUTF16_bigendian_internal(char * s1, int len1, char * s2, stbtt_uint32 s2offs, int len2)
{
return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8 *)s1, len1, (stbtt_uint8 *)s2, s2offs, len2);
}
#endif
// returns results in whatever encoding you request... but note that 2-byte encodings
// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
STBTT_DEF stbtt_uint32 stbtt_GetFontNameString(const stbtt_fontinfo * font, int * length, int platformID,
int encodingID, int languageID, int nameID)
{
stbtt_int32 i, count, stringOffset;
stbtt_uint32 offset = font->fontstart;
stbtt_uint32 nm = stbtt__find_table(font->data, offset, "name");
if(!nm) return 0;
count = ttUSHORT(font->data, nm + 2);
stringOffset = nm + ttUSHORT(font->data, nm + 4);
for(i = 0; i < count; ++i) {
stbtt_uint32 loc = nm + 6 + 12 * i;
if(platformID == ttUSHORT(font->data, loc + 0) && encodingID == ttUSHORT(font->data, loc + 2)
&& languageID == ttUSHORT(font->data, loc + 4) && nameID == ttUSHORT(font->data, loc + 6)) {
*length = ttUSHORT(font->data, loc + 8);
return stringOffset + ttUSHORT(font->data, loc + 10);
}
}
return 0;
}
#ifdef STBTT_STREAM_TYPE
static int stbtt__matchpair(STBTT_STREAM_TYPE fc, stbtt_uint32 nm, stbtt_uint8 * name, stbtt_int32 nlen,
stbtt_int32 target_id, stbtt_int32 next_id)
#else
static int stbtt__matchpair(stbtt_uint8 * fc, stbtt_uint32 nm, stbtt_uint8 * name, stbtt_int32 nlen,
stbtt_int32 target_id, stbtt_int32 next_id)
#endif
{
stbtt_int32 i;
stbtt_int32 count = ttUSHORT(fc, nm + 2);
stbtt_int32 stringOffset = nm + ttUSHORT(fc, nm + 4);
for(i = 0; i < count; ++i) {
stbtt_uint32 loc = nm + 6 + 12 * i;
stbtt_int32 id = ttUSHORT(fc, loc + 6);
if(id == target_id) {
// find the encoding
stbtt_int32 platform = ttUSHORT(fc, loc + 0), encoding = ttUSHORT(fc, loc + 2), language = ttUSHORT(fc, loc + 4);
// is this a Unicode encoding?
if(platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {
stbtt_int32 slen = ttUSHORT(fc, loc + 8);
stbtt_int32 off = ttUSHORT(fc, loc + 10);
// check if there's a prefix match
stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc, stringOffset + off, slen);
if(matchlen >= 0) {
// check for target_id+1 immediately following, with same encoding & language
if(i + 1 < count && ttUSHORT(fc, loc + 12 + 6) == next_id && ttUSHORT(fc, loc + 12) == platform &&
ttUSHORT(fc, loc + 12 + 2) == encoding && ttUSHORT(fc, loc + 12 + 4) == language) {
slen = ttUSHORT(fc, loc + 12 + 8);
off = ttUSHORT(fc, loc + 12 + 10);
if(slen == 0) {
if(matchlen == nlen)
return 1;
}
else if(matchlen < nlen && name[matchlen] == ' ') {
++matchlen;
#ifdef STBTT_STREAM_TYPE
if(stbtt_CompareUTF8toUTF16_bigendian_internal((char *)(name + matchlen), nlen - matchlen, fc, stringOffset + off,
slen))
#else
if(stbtt_CompareUTF8toUTF16_bigendian_internal((char *)(name + matchlen), nlen - matchlen, (char *)fc,
stringOffset + off, slen))
#endif
return 1;
}
}
else {
// if nothing immediately following
if(matchlen == nlen)
return 1;
}
}
}
// @TODO handle other encodings
}
}
return 0;
}
#ifdef STBTT_STREAM_TYPE
static int stbtt__matches(STBTT_STREAM_TYPE fc, stbtt_uint32 offset, stbtt_uint8 * name, stbtt_int32 flags)
#else
static int stbtt__matches(stbtt_uint8 * fc, stbtt_uint32 offset, stbtt_uint8 * name, stbtt_int32 flags)
#endif
{
stbtt_int32 nlen = (stbtt_int32)STBTT_strlen((char *)name);
stbtt_uint32 nm, hd;
if(!stbtt__isfont(fc, offset)) return 0;
// check italics/bold/underline flags in macStyle...
if(flags) {
hd = stbtt__find_table(fc, offset, "head");
if((ttUSHORT(fc, hd + 44) & 7) != (flags & 7)) return 0;
}
nm = stbtt__find_table(fc, offset, "name");
if(!nm) return 0;
if(flags) {
if(name == NULL) return 1;
// if we checked the macStyle flags, then just check the family and ignore the subfamily
if(stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1;
if(stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1;
if(stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
}
else {
if(name == NULL) return 1;
if(stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1;
if(stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1;
if(stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
}
return 0;
}
#ifdef STBTT_STREAM_TYPE
static int stbtt_FindMatchingFont_internal(STBTT_STREAM_TYPE font_collection, char * name_utf8, stbtt_int32 flags)
#else
static int stbtt_FindMatchingFont_internal(unsigned char * font_collection, char * name_utf8, stbtt_int32 flags)
#endif
{
stbtt_int32 i;
for(i = 0;; ++i) {
stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
if(off < 0) return off;
#ifdef STBTT_STREAM_TYPE
if(stbtt__matches(font_collection, off, (stbtt_uint8 *)name_utf8, flags))
#else
if(stbtt__matches((stbtt_uint8 *)font_collection, off, (stbtt_uint8 *)name_utf8, flags))
#endif
return off;
}
}
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
#endif
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_BakeFontBitmap(STBTT_STREAM_TYPE data, int offset,
float pixel_height, unsigned char * pixels, int pw, int ph,
int first_char, int num_chars, stbtt_bakedchar * chardata);
#else
STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char * data, int offset,
float pixel_height, unsigned char * pixels, int pw, int ph,
int first_char, int num_chars, stbtt_bakedchar * chardata);
#endif
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_BakeFontBitmap(STBTT_STREAM_TYPE data, int offset,
float pixel_height, unsigned char * pixels, int pw, int ph,
int first_char, int num_chars, stbtt_bakedchar * chardata)
#else
STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char * data, int offset,
float pixel_height, unsigned char * pixels, int pw, int ph,
int first_char, int num_chars, stbtt_bakedchar * chardata)
#endif
{
#ifdef STBTT_STREAM_TYPE
return stbtt_BakeFontBitmap_internal(data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata);
#else
return stbtt_BakeFontBitmap_internal((unsigned char *)data, offset, pixel_height, pixels, pw, ph, first_char, num_chars,
chardata);
#endif
}
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_GetFontOffsetForIndex(STBTT_STREAM_TYPE data, int index)
{
return stbtt_GetFontOffsetForIndex_internal(data, index);
}
#else
STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char * data, int index)
{
return stbtt_GetFontOffsetForIndex_internal((unsigned char *)data, index);
}
#endif
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_GetNumberOfFonts(STBTT_STREAM_TYPE data)
{
return stbtt_GetNumberOfFonts_internal(data);
}
#else
STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char * data)
{
return stbtt_GetNumberOfFonts_internal((unsigned char *)data);
}
#endif
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_InitFont(stbtt_fontinfo * info, STBTT_STREAM_TYPE data, int offset)
{
return stbtt_InitFont_internal(info, data, offset);
}
#else
STBTT_DEF int stbtt_InitFont(stbtt_fontinfo * info, const unsigned char * data, int offset)
{
return stbtt_InitFont_internal(info, (unsigned char *)data, offset);
}
#endif
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_FindMatchingFont(STBTT_STREAM_TYPE fontdata, const char * name, int flags)
{
return stbtt_FindMatchingFont_internal(fontdata, (char *)name, flags);
}
#else
STBTT_DEF int stbtt_FindMatchingFont(const unsigned char * fontdata, const char * name, int flags)
{
return stbtt_FindMatchingFont_internal((unsigned char *)fontdata, (char *)name, flags);
}
#endif
#ifdef STBTT_STREAM_TYPE
STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char * s1, int len1, STBTT_STREAM_TYPE s2, stbtt_uint32 s2offs,
int len2)
{
return stbtt_CompareUTF8toUTF16_bigendian_internal((char *)s1, len1, s2, s2offs, len2);
}
#else
STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char * s1, int len1, const char * s2, stbtt_uint32 s2offs,
int len2)
{
return stbtt_CompareUTF8toUTF16_bigendian_internal((char *)s1, len1, (char *)s2, s2offs, len2);
}
#endif
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#pragma GCC diagnostic pop
#endif
#endif // STB_TRUETYPE_IMPLEMENTATION
// FULL VERSION HISTORY
//
// 1.25 (2021-07-11) many fixes
// 1.24 (2020-02-05) fix warning
// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS)
// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined
// 1.21 (2019-02-25) fix warning
// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()
// 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod
// 1.18 (2018-01-29) add missing function
// 1.17 (2017-07-23) make more arguments const; doc fix
// 1.16 (2017-07-12) SDF support
// 1.15 (2017-03-03) make more arguments const
// 1.14 (2017-01-16) num-fonts-in-TTC function
// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
// 1.11 (2016-04-02) fix unused-variable warning
// 1.10 (2016-04-02) allow user-defined fabs() replacement
// fix memory leak if fontsize=0.0
// fix warning from duplicate typedef
// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges
// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
// allow PackFontRanges to pack and render in separate phases;
// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
// fixed an assert() bug in the new rasterizer
// replace assert() with STBTT_assert() in new rasterizer
// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)
// also more precise AA rasterizer, except if shapes overlap
// remove need for STBTT_sort
// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC
// 1.04 (2015-04-15) typo in example
// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes
// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++
// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match
// non-oversampled; STBTT_POINT_SIZE for packed case only
// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling
// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)
// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID
// 0.8b (2014-07-07) fix a warning
// 0.8 (2014-05-25) fix a few more warnings
// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
// 0.6c (2012-07-24) improve documentation
// 0.6b (2012-07-20) fix a few more warnings
// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
// 0.5 (2011-12-09) bugfixes:
// subpixel glyph renderer computed wrong bounding box
// first vertex of shape can be off-curve (FreeSans)
// 0.4b (2011-12-03) fixed an error in the font baking example
// 0.4 (2011-12-01) kerning, subpixel rendering (tor)
// bugfixes for:
// codepoint-to-glyph conversion using table fmt=12
// codepoint-to-glyph conversion using table fmt=4
// stbtt_GetBakedQuad with non-square texture (Zer)
// updated Hello World! sample to use kerning and subpixel
// fixed some warnings
// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM)
// userdata, malloc-from-userdata, non-zero fill (stb)
// 0.2 (2009-03-11) Fix unsigned/signed char warnings
// 0.1 (2009-03-09) First public release
//
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/tiny_ttf/lv_tiny_ttf.c | #include "lv_tiny_ttf.h"
#if LV_USE_TINY_TTF
#include <stdio.h>
#define STB_RECT_PACK_IMPLEMENTATION
#define STBRP_STATIC
#define STBTT_STATIC
#define STB_TRUETYPE_IMPLEMENTATION
#define STBTT_HEAP_FACTOR_SIZE_32 50
#define STBTT_HEAP_FACTOR_SIZE_128 20
#define STBTT_HEAP_FACTOR_SIZE_DEFAULT 10
#define STBTT_malloc(x, u) ((void)(u), lv_malloc(x))
#define STBTT_free(x, u) ((void)(u), lv_free(x))
#define TTF_MALLOC(x) (lv_malloc(x))
#define TTF_FREE(x) (lv_free(x))
#if LV_TINY_TTF_FILE_SUPPORT != 0
/* a hydra stream that can be in memory or from a file*/
typedef struct ttf_cb_stream {
lv_fs_file_t * file;
const void * data;
size_t size;
size_t position;
} ttf_cb_stream_t;
static void ttf_cb_stream_read(ttf_cb_stream_t * stream, void * data, size_t to_read)
{
if(stream->file != NULL) {
uint32_t br;
lv_fs_read(stream->file, data, to_read, &br);
}
else {
if(to_read + stream->position >= stream->size) {
to_read = stream->size - stream->position;
}
memcpy(data, ((const unsigned char *)stream->data + stream->position), to_read);
stream->position += to_read;
}
}
static void ttf_cb_stream_seek(ttf_cb_stream_t * stream, size_t position)
{
if(stream->file != NULL) {
lv_fs_seek(stream->file, position, LV_FS_SEEK_SET);
}
else {
if(position > stream->size) {
stream->position = stream->size;
}
else {
stream->position = position;
}
}
}
/* for stream support */
#define STBTT_STREAM_TYPE ttf_cb_stream_t *
#define STBTT_STREAM_SEEK(s, x) ttf_cb_stream_seek(s, x);
#define STBTT_STREAM_READ(s, x, y) ttf_cb_stream_read(s, x, y);
#endif
#include "stb_rect_pack.h"
#include "stb_truetype_htcw.h"
typedef struct ttf_font_desc {
lv_fs_file_t file;
#if LV_TINY_TTF_FILE_SUPPORT != 0
ttf_cb_stream_t stream;
#else
const uint8_t * stream;
#endif
stbtt_fontinfo info;
float scale;
int ascent;
int descent;
} ttf_font_desc_t;
typedef struct ttf_cache_entry {
uint8_t * buffer;
} ttf_cache_entry_t;
static bool ttf_get_glyph_dsc_cb(const lv_font_t * font, lv_font_glyph_dsc_t * dsc_out, uint32_t unicode_letter,
uint32_t unicode_letter_next)
{
if(unicode_letter < 0x20 ||
unicode_letter == 0xf8ff || /*LV_SYMBOL_DUMMY*/
unicode_letter == 0x200c) { /*ZERO WIDTH NON-JOINER*/
dsc_out->box_w = 0;
dsc_out->adv_w = 0;
dsc_out->box_h = 0; /*height of the bitmap in [px]*/
dsc_out->ofs_x = 0; /*X offset of the bitmap in [pf]*/
dsc_out->ofs_y = 0; /*Y offset of the bitmap in [pf]*/
dsc_out->bpp = 0;
dsc_out->is_placeholder = false;
return true;
}
ttf_font_desc_t * dsc = (ttf_font_desc_t *)font->dsc;
int g1 = stbtt_FindGlyphIndex(&dsc->info, (int)unicode_letter);
if(g1 == 0) {
/* Glyph not found */
return false;
}
int x1, y1, x2, y2;
stbtt_GetGlyphBitmapBox(&dsc->info, g1, dsc->scale, dsc->scale, &x1, &y1, &x2, &y2);
int g2 = 0;
if(unicode_letter_next != 0) {
g2 = stbtt_FindGlyphIndex(&dsc->info, (int)unicode_letter_next);
}
int advw, lsb;
stbtt_GetGlyphHMetrics(&dsc->info, g1, &advw, &lsb);
int k = stbtt_GetGlyphKernAdvance(&dsc->info, g1, g2);
dsc_out->adv_w = (uint16_t)floor((((float)advw + (float)k) * dsc->scale) +
0.5f); /*Horizontal space required by the glyph in [px]*/
dsc_out->adv_w = (uint16_t)floor((((float)advw + (float)k) * dsc->scale) +
0.5f); /*Horizontal space required by the glyph in [px]*/
dsc_out->box_w = (x2 - x1 + 1); /*width of the bitmap in [px]*/
dsc_out->box_h = (y2 - y1 + 1); /*height of the bitmap in [px]*/
dsc_out->ofs_x = x1; /*X offset of the bitmap in [pf]*/
dsc_out->ofs_y = -y2; /*Y offset of the bitmap measured from the as line*/
dsc_out->bpp = 8; /*Bits per pixel: 1/2/4/8*/
dsc_out->is_placeholder = false;
return true; /*true: glyph found; false: glyph was not found*/
}
static const uint8_t * ttf_get_glyph_bitmap_cb(const lv_font_t * font, uint32_t unicode_letter, uint8_t * bitmap_buf)
{
LV_UNUSED(bitmap_buf);
ttf_font_desc_t * dsc = (ttf_font_desc_t *)font->dsc;
const stbtt_fontinfo * info = (const stbtt_fontinfo *)&dsc->info;
int g1 = stbtt_FindGlyphIndex(info, (int)unicode_letter);
if(g1 == 0) {
/* Glyph not found */
return NULL;
}
int x1, y1, x2, y2;
stbtt_GetGlyphBitmapBox(info, g1, dsc->scale, dsc->scale, &x1, &y1, &x2, &y2);
int w, h;
w = x2 - x1 + 1;
h = y2 - y1 + 1;
uint32_t stride = lv_draw_buf_width_to_stride(w, LV_COLOR_FORMAT_A8);
lv_cache_lock();
uint32_t cp = unicode_letter;
lv_cache_entry_t * cache = lv_cache_find(font, LV_CACHE_SRC_TYPE_PTR, font->line_height, cp);
if(cache) {
uint8_t * buffer = (uint8_t *)lv_cache_get_data(cache);
lv_cache_unlock();
return buffer;
}
size_t szb = h * stride;
lv_cache_entry_t * entry = lv_cache_add(szb);
if(entry == NULL) {
lv_cache_unlock();
LV_LOG_ERROR("tiny_ttf: cache not allocated\n");
return NULL;
}
/* This smells. We add the codepoint to the base pointer to get a key. */
entry->src = font;
entry->src_type = LV_CACHE_SRC_TYPE_PTR;
entry->param1 = font->line_height;
entry->param2 = cp;
uint8_t * buffer = lv_draw_buf_malloc(szb, LV_COLOR_FORMAT_A8);
if(NULL == buffer) {
LV_LOG_ERROR("tiny_ttf: out of memory\n");
lv_cache_invalidate(entry);
lv_cache_unlock();
return NULL;
}
entry->data = buffer;
entry->free_data = 1;
memset(buffer, 0, szb);
stbtt_MakeGlyphBitmap(info, buffer, w, h, stride, dsc->scale, dsc->scale, g1);
lv_cache_unlock();
return buffer; /*Or NULL if not found*/
}
static lv_font_t * lv_tiny_ttf_create(const char * path, const void * data, size_t data_size, int32_t font_size,
size_t cache_size)
{
LV_UNUSED(data_size);
LV_UNUSED(cache_size);
if((path == NULL && data == NULL) || 0 >= font_size) {
LV_LOG_ERROR("tiny_ttf: invalid argument\n");
return NULL;
}
ttf_font_desc_t * dsc = (ttf_font_desc_t *)TTF_MALLOC(sizeof(ttf_font_desc_t));
if(dsc == NULL) {
LV_LOG_ERROR("tiny_ttf: out of memory\n");
return NULL;
}
#if LV_TINY_TTF_FILE_SUPPORT != 0
if(path != NULL) {
if(LV_FS_RES_OK != lv_fs_open(&dsc->file, path, LV_FS_MODE_RD)) {
TTF_FREE(dsc);
LV_LOG_ERROR("tiny_ttf: unable to open %s\n", path);
return NULL;
}
dsc->stream.file = &dsc->file;
}
else {
dsc->stream.file = NULL;
dsc->stream.data = (const uint8_t *)data;
dsc->stream.size = data_size;
dsc->stream.position = 0;
}
if(0 == stbtt_InitFont(&dsc->info, &dsc->stream, stbtt_GetFontOffsetForIndex(&dsc->stream, 0))) {
TTF_FREE(dsc);
LV_LOG_ERROR("tiny_ttf: init failed\n");
return NULL;
}
#else
dsc->stream = (const uint8_t *)data;
if(0 == stbtt_InitFont(&dsc->info, dsc->stream, stbtt_GetFontOffsetForIndex(dsc->stream, 0))) {
TTF_FREE(dsc);
LV_LOG_ERROR("tiny_ttf: init failed\n");
return NULL;
}
#endif
lv_font_t * out_font = (lv_font_t *)TTF_MALLOC(sizeof(lv_font_t));
if(out_font == NULL) {
TTF_FREE(dsc);
LV_LOG_ERROR("tiny_ttf: out of memory\n");
return NULL;
}
lv_memzero(out_font, sizeof(lv_font_t));
out_font->get_glyph_dsc = ttf_get_glyph_dsc_cb;
out_font->get_glyph_bitmap = ttf_get_glyph_bitmap_cb;
out_font->dsc = dsc;
lv_tiny_ttf_set_size(out_font, font_size);
return out_font;
}
#if LV_TINY_TTF_FILE_SUPPORT != 0
lv_font_t * lv_tiny_ttf_create_file_ex(const char * path, int32_t font_size, size_t cache_size)
{
return lv_tiny_ttf_create(path, NULL, 0, font_size, cache_size);
}
lv_font_t * lv_tiny_ttf_create_file(const char * path, int32_t font_size)
{
return lv_tiny_ttf_create(path, NULL, 0, font_size, 0);
}
#endif
lv_font_t * lv_tiny_ttf_create_data_ex(const void * data, size_t data_size, int32_t font_size, size_t cache_size)
{
return lv_tiny_ttf_create(NULL, data, data_size, font_size, cache_size);
}
lv_font_t * lv_tiny_ttf_create_data(const void * data, size_t data_size, int32_t font_size)
{
return lv_tiny_ttf_create(NULL, data, data_size, font_size, 0);
}
void lv_tiny_ttf_set_size(lv_font_t * font, int32_t font_size)
{
if(font_size <= 0) {
LV_LOG_ERROR("invalid font size: %"PRIx32, font_size);
return;
}
ttf_font_desc_t * dsc = (ttf_font_desc_t *)font->dsc;
dsc->scale = stbtt_ScaleForMappingEmToPixels(&dsc->info, font_size);
int line_gap = 0;
stbtt_GetFontVMetrics(&dsc->info, &dsc->ascent, &dsc->descent, &line_gap);
font->line_height = (int32_t)(dsc->scale * (dsc->ascent - dsc->descent + line_gap));
font->base_line = (int32_t)(dsc->scale * (line_gap - dsc->descent));
}
void lv_tiny_ttf_destroy(lv_font_t * font)
{
if(font != NULL) {
if(font->dsc != NULL) {
ttf_font_desc_t * ttf = (ttf_font_desc_t *)font->dsc;
#if LV_TINY_TTF_FILE_SUPPORT != 0
if(ttf->stream.file != NULL) {
lv_fs_close(&ttf->file);
}
#endif
TTF_FREE(ttf);
}
TTF_FREE(font);
}
}
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/tiny_ttf/lv_tiny_ttf.h | /**
* @file lv_templ.h
*
*/
#ifndef LV_TINY_TTF_H
#define LV_TINY_TTF_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_TINY_TTF
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
#if LV_TINY_TTF_FILE_SUPPORT !=0
/* create a font from the specified file or path with the specified line height.*/
lv_font_t * lv_tiny_ttf_create_file(const char * path, int32_t font_size);
/* create a font from the specified file or path with the specified line height with the specified cache size.*/
lv_font_t * lv_tiny_ttf_create_file_ex(const char * path, int32_t font_size, size_t cache_size);
#endif
/* create a font from the specified data pointer with the specified line height.*/
lv_font_t * lv_tiny_ttf_create_data(const void * data, size_t data_size, int32_t font_size);
/* create a font from the specified data pointer with the specified line height and the specified cache size.*/
lv_font_t * lv_tiny_ttf_create_data_ex(const void * data, size_t data_size, int32_t font_size, size_t cache_size);
/* set the size of the font to a new font_size*/
void lv_tiny_ttf_set_size(lv_font_t * font, int32_t font_size);
/* destroy a font previously created with lv_tiny_ttf_create_xxxx()*/
void lv_tiny_ttf_destroy(lv_font_t * font);
/**********************
* MACROS
**********************/
#endif /*LV_USE_TINY_TTF*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_TINY_TTF_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/tjpgd/tjpgd.h | /*----------------------------------------------------------------------------/
/ TJpgDec - Tiny JPEG Decompressor R0.03 include file (C)ChaN, 2021
/----------------------------------------------------------------------------*/
#ifndef DEF_TJPGDEC
#define DEF_TJPGDEC
#ifdef __cplusplus
extern "C" {
#endif
#include "tjpgdcnf.h"
#include <string.h>
#if defined(_WIN32) /* VC++ or some compiler without stdint.h */
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef short int16_t;
typedef unsigned long uint32_t;
typedef long int32_t;
#else /* Embedded platform */
#include <stdint.h>
#endif
#if JD_FASTDECODE >= 1
typedef int16_t jd_yuv_t;
#else
typedef uint8_t jd_yuv_t;
#endif
/* Error code */
typedef enum {
JDR_OK = 0, /* 0: Succeeded */
JDR_INTR, /* 1: Interrupted by output function */
JDR_INP, /* 2: Device error or wrong termination of input stream */
JDR_MEM1, /* 3: Insufficient memory pool for the image */
JDR_MEM2, /* 4: Insufficient stream input buffer */
JDR_PAR, /* 5: Parameter error */
JDR_FMT1, /* 6: Data format error (may be broken data) */
JDR_FMT2, /* 7: Right format but not supported */
JDR_FMT3 /* 8: Not supported JPEG standard */
} JRESULT;
/* Rectangular region in the output image */
typedef struct {
uint16_t left; /* Left end */
uint16_t right; /* Right end */
uint16_t top; /* Top end */
uint16_t bottom; /* Bottom end */
} JRECT;
/* Decompressor object structure */
typedef struct JDEC JDEC;
struct JDEC {
size_t dctr; /* Number of bytes available in the input buffer */
uint8_t * dptr; /* Current data read ptr */
uint8_t * inbuf; /* Bit stream input buffer */
uint8_t dbit; /* Number of bits availavble in wreg or reading bit mask */
uint8_t scale; /* Output scaling ratio */
uint8_t msx, msy; /* MCU size in unit of block (width, height) */
uint8_t qtid[3]; /* Quantization table ID of each component, Y, Cb, Cr */
uint8_t ncomp; /* Number of color components 1:grayscale, 3:color */
int16_t dcv[3]; /* Previous DC element of each component */
uint16_t nrst; /* Restart inverval */
uint16_t rst; /* Restart count*/
uint16_t rsc; /* Expected restart sequence ID*/
uint16_t width, height; /* Size of the input image (pixel) */
uint8_t * huffbits[2][2]; /* Huffman bit distribution tables [id][dcac] */
uint16_t * huffcode[2][2]; /* Huffman code word tables [id][dcac] */
uint8_t * huffdata[2][2]; /* Huffman decoded data tables [id][dcac] */
int32_t * qttbl[4]; /* Dequantizer tables [id] */
#if JD_FASTDECODE >= 1
uint32_t wreg; /* Working shift register */
uint8_t marker; /* Detected marker (0:None) */
#if JD_FASTDECODE == 2
uint8_t longofs[2][2]; /* Table offset of long code [id][dcac] */
uint16_t * hufflut_ac[2]; /* Fast huffman decode tables for AC short code [id] */
uint8_t * hufflut_dc[2]; /* Fast huffman decode tables for DC short code [id] */
#endif
#endif
void * workbuf; /* Working buffer for IDCT and RGB output */
jd_yuv_t * mcubuf; /* Working buffer for the MCU */
void * pool; /* Pointer to available memory pool */
void * pool_original; /* Pointer to original pool */
size_t sz_pool; /* Size of momory pool (bytes available) */
size_t (*infunc)(JDEC *, uint8_t *, size_t); /* Pointer to jpeg stream input function */
void * device; /* Pointer to I/O device identifiler for the session */
};
/* TJpgDec API functions */
JRESULT jd_prepare(JDEC * jd, size_t (*infunc)(JDEC *, uint8_t *, size_t), void * pool, size_t sz_pool, void * dev);
JRESULT jd_decomp(JDEC * jd, int (*outfunc)(JDEC *, void *, JRECT *), uint8_t scale);
JRESULT jd_mcu_load(JDEC * jd);
JRESULT jd_mcu_output(JDEC * jd, int (*outfunc)(JDEC *, void *, JRECT *), unsigned int x, unsigned int y);
JRESULT jd_restart(JDEC * jd, uint16_t rstn);
#ifdef __cplusplus
}
#endif
#endif /* _TJPGDEC */
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/tjpgd/lv_tjpgd.c | /**
* @file lv_tjpgd.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_TJPGD
#include "tjpgd.h"
#include "lv_tjpgd.h"
#include "../../misc/lv_fs.h"
/*********************
* DEFINES
*********************/
#define TJPGD_WORKBUFF_SIZE 4096 //Recommended by TJPGD library
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static lv_result_t decoder_info(lv_image_decoder_t * decoder, const void * src, lv_image_header_t * header);
static lv_result_t decoder_open(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc);
static lv_result_t decoder_get_area(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc,
const lv_area_t * full_area, lv_area_t * decoded_area);
static void decoder_close(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc);
static size_t input_func(JDEC * jd, uint8_t * buff, size_t ndata);
static int is_jpg(const uint8_t * raw_data, size_t len);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_tjpgd_init(void)
{
lv_image_decoder_t * dec = lv_image_decoder_create();
lv_image_decoder_set_info_cb(dec, decoder_info);
lv_image_decoder_set_open_cb(dec, decoder_open);
lv_image_decoder_set_get_area_cb(dec, decoder_get_area);
lv_image_decoder_set_close_cb(dec, decoder_close);
}
void lv_tjpgd_deinit(void)
{
lv_image_decoder_t * dec = NULL;
while((dec = lv_image_decoder_get_next(dec)) != NULL) {
if(dec->info_cb == decoder_info) {
lv_image_decoder_delete(dec);
break;
}
}
}
/**********************
* STATIC FUNCTIONS
**********************/
static lv_result_t decoder_info(lv_image_decoder_t * decoder, const void * src, lv_image_header_t * header)
{
LV_UNUSED(decoder);
lv_image_src_t src_type = lv_image_src_get_type(src);
if(src_type == LV_IMAGE_SRC_VARIABLE) {
const lv_image_dsc_t * img_dsc = src;
uint8_t * raw_data = (uint8_t *)img_dsc->data;
const uint32_t raw_sjpeg_data_size = img_dsc->data_size;
if(is_jpg(raw_data, raw_sjpeg_data_size) == true) {
#if LV_USE_FS_MEMFS
header->always_zero = 0;
header->cf = LV_COLOR_FORMAT_RAW;
header->w = img_dsc->header.w;
header->h = img_dsc->header.h;
header->stride = img_dsc->header.w * 3;
return LV_RESULT_OK;
#else
LV_LOG_WARN("LV_USE_FS_MEMFS needs to enabled to decode from data");
return LV_RESULT_INVALID;
#endif
}
}
else if(src_type == LV_IMAGE_SRC_FILE) {
const char * fn = src;
if((strcmp(lv_fs_get_ext(fn), "jpg") == 0) || (strcmp(lv_fs_get_ext(fn), "jpeg") == 0)) {
lv_fs_file_t f;
lv_fs_res_t res;
res = lv_fs_open(&f, fn, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) return LV_RESULT_INVALID;
uint8_t workb[TJPGD_WORKBUFF_SIZE];
JDEC jd;
JRESULT rc = jd_prepare(&jd, input_func, workb, TJPGD_WORKBUFF_SIZE, &f);
if(rc) {
LV_LOG_WARN("jd_prepare error: %d", rc);
lv_fs_close(&f);
return LV_RESULT_INVALID;
}
header->always_zero = 0;
header->cf = LV_COLOR_FORMAT_RAW;
header->w = jd.width;
header->h = jd.height;
header->stride = jd.width * 3;
lv_fs_close(&f);
return LV_RESULT_OK;
}
}
return LV_RESULT_INVALID;
}
static size_t input_func(JDEC * jd, uint8_t * buff, size_t ndata)
{
lv_fs_file_t * f = jd->device;
if(!f) return 0;
if(buff) {
uint32_t rn = 0;
lv_fs_read(f, buff, (uint32_t)ndata, &rn);
return rn;
}
else {
uint32_t pos;
lv_fs_tell(f, &pos);
lv_fs_seek(f, (uint32_t)(ndata + pos), LV_FS_SEEK_SET);
return ndata;
}
return 0;
}
static lv_result_t decoder_open(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder);
lv_fs_file_t * f = lv_malloc(sizeof(lv_fs_file_t));
if(dsc->src_type == LV_IMAGE_SRC_VARIABLE) {
#if LV_USE_FS_MEMFS
const lv_image_dsc_t * img_dsc = dsc->src;
if(is_jpg(img_dsc->data, img_dsc->data_size) == true) {
lv_fs_path_ex_t path;
lv_fs_make_path_from_buffer(&path, LV_FS_MEMFS_LETTER, img_dsc->data, img_dsc->data_size);
lv_fs_res_t res;
res = lv_fs_open(f, (const char *)&path, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) {
lv_free(f);
return LV_RESULT_INVALID;
}
}
#else
LV_LOG_WARN("LV_USE_FS_MEMFS needs to enabled to decode from data");
return LV_RESULT_INVALID;
#endif
}
else if(dsc->src_type == LV_IMAGE_SRC_FILE) {
const char * fn = dsc->src;
if((strcmp(lv_fs_get_ext(fn), "jpg") == 0) || (strcmp(lv_fs_get_ext(fn), "jpeg") == 0)) {
lv_fs_res_t res;
res = lv_fs_open(f, fn, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) {
lv_free(f);
return LV_RESULT_INVALID;
}
}
}
uint8_t * workb_temp = lv_malloc(TJPGD_WORKBUFF_SIZE);
JDEC * jd = lv_malloc(sizeof(JDEC));
dsc->user_data = jd;
JRESULT rc = jd_prepare(jd, input_func, workb_temp, (size_t)TJPGD_WORKBUFF_SIZE, f);
if(rc) return rc;
dsc->header.always_zero = 0;
dsc->header.cf = LV_COLOR_FORMAT_RGB888;
dsc->header.w = jd->width;
dsc->header.h = jd->height;
dsc->header.stride = jd->width * 3;
if(rc != JDR_OK) {
lv_free(workb_temp);
lv_free(jd);
return LV_RESULT_INVALID;
}
return LV_RESULT_OK;
}
static lv_result_t decoder_get_area(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc,
const lv_area_t * full_area, lv_area_t * decoded_area)
{
LV_UNUSED(decoder);
LV_UNUSED(full_area);
JDEC * jd = dsc->user_data;
uint32_t mx, my;
mx = jd->msx * 8;
my = jd->msy * 8; /* Size of the MCU (pixel) */
if(decoded_area->y1 == LV_COORD_MIN) {
decoded_area->y1 = 0;
decoded_area->y2 = my - 1;
decoded_area->x1 = -mx;
decoded_area->x2 = -1;
jd->scale = 0;
jd->dcv[2] = jd->dcv[1] = jd->dcv[0] = 0; /* Initialize DC values */
dsc->img_data = jd->workbuf;
jd->rst = 0;
jd->rsc = 0;
dsc->header.stride = mx * 3;
}
decoded_area->x1 += mx;
decoded_area->x2 += mx;
if(decoded_area->x1 >= jd->width) {
decoded_area->x1 = 0;
decoded_area->x2 = mx - 1;
decoded_area->y1 += my;
decoded_area->y2 += my;
}
/* Process restart interval if enabled */
JRESULT rc;
if(jd->nrst && jd->rst++ == jd->nrst) {
rc = jd_restart(jd, jd->rsc++);
if(rc != JDR_OK) return rc;
jd->rst = 1;
}
/* Load an MCU (decompress huffman coded stream, dequantize and apply IDCT) */
rc = jd_mcu_load(jd);
if(rc != JDR_OK) return rc;
/* Output the MCU (YCbCr to RGB, scaling and output) */
rc = jd_mcu_output(jd, NULL, decoded_area->x1, decoded_area->y1);
if(rc != JDR_OK) return rc;
return LV_RESULT_OK;
}
/**
* Free the allocated resources
* @param decoder pointer to the decoder where this function belongs
* @param dsc pointer to a descriptor which describes this decoding session
*/
static void decoder_close(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder);
JDEC * jd = dsc->user_data;
lv_fs_close(jd->device);
lv_free(jd->device);
lv_free(jd->pool_original);
lv_free(jd);
}
static int is_jpg(const uint8_t * raw_data, size_t len)
{
const uint8_t jpg_signature[] = {0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46};
if(len < sizeof(jpg_signature)) return false;
return memcmp(jpg_signature, raw_data, sizeof(jpg_signature)) == 0;
}
#endif /*LV_USE_TJPGD*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/tjpgd/tjpgd.c | /*----------------------------------------------------------------------------/
/ TJpgDec - Tiny JPEG Decompressor R0.03 (C)ChaN, 2021
/-----------------------------------------------------------------------------/
/ The TJpgDec is a generic JPEG decompressor module for tiny embedded systems.
/ This is a free software that opened for education, research and commercial
/ developments under license policy of following terms.
/
/ Copyright (C) 2021, ChaN, all right reserved.
/
/ * The TJpgDec module is a free software and there is NO WARRANTY.
/ * No restriction on use. You can use, modify and redistribute it for
/ personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY.
/ * Redistributions of source code must retain the above copyright notice.
/
/-----------------------------------------------------------------------------/
/ Oct 04, 2011 R0.01 First release.
/ Feb 19, 2012 R0.01a Fixed decompression fails when scan starts with an escape seq.
/ Sep 03, 2012 R0.01b Added JD_TBLCLIP option.
/ Mar 16, 2019 R0.01c Supprted stdint.h.
/ Jul 01, 2020 R0.01d Fixed wrong integer type usage.
/ May 08, 2021 R0.02 Supprted grayscale image. Separated configuration options.
/ Jun 11, 2021 R0.02a Some performance improvement.
/ Jul 01, 2021 R0.03 Added JD_FASTDECODE option.
/ Some performance improvement.
/----------------------------------------------------------------------------*/
#include "tjpgd.h"
#if JD_FASTDECODE == 2
#define HUFF_BIT 10 /* Bit length to apply fast huffman decode */
#define HUFF_LEN (1 << HUFF_BIT)
#define HUFF_MASK (HUFF_LEN - 1)
#endif
/*-----------------------------------------------*/
/* Zigzag-order to raster-order conversion table */
/*-----------------------------------------------*/
static const uint8_t Zig[64] = { /* Zigzag-order to raster-order conversion table */
0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63
};
/*-------------------------------------------------*/
/* Input scale factor of Arai algorithm */
/* (scaled up 16 bits for fixed point operations) */
/*-------------------------------------------------*/
static const uint16_t Ipsf[64] = { /* See also aa_idct.png */
(uint16_t)(1.00000 * 8192), (uint16_t)(1.38704 * 8192), (uint16_t)(1.30656 * 8192), (uint16_t)(1.17588 * 8192), (uint16_t)(1.00000 * 8192), (uint16_t)(0.78570 * 8192), (uint16_t)(0.54120 * 8192), (uint16_t)(0.27590 * 8192),
(uint16_t)(1.38704 * 8192), (uint16_t)(1.92388 * 8192), (uint16_t)(1.81226 * 8192), (uint16_t)(1.63099 * 8192), (uint16_t)(1.38704 * 8192), (uint16_t)(1.08979 * 8192), (uint16_t)(0.75066 * 8192), (uint16_t)(0.38268 * 8192),
(uint16_t)(1.30656 * 8192), (uint16_t)(1.81226 * 8192), (uint16_t)(1.70711 * 8192), (uint16_t)(1.53636 * 8192), (uint16_t)(1.30656 * 8192), (uint16_t)(1.02656 * 8192), (uint16_t)(0.70711 * 8192), (uint16_t)(0.36048 * 8192),
(uint16_t)(1.17588 * 8192), (uint16_t)(1.63099 * 8192), (uint16_t)(1.53636 * 8192), (uint16_t)(1.38268 * 8192), (uint16_t)(1.17588 * 8192), (uint16_t)(0.92388 * 8192), (uint16_t)(0.63638 * 8192), (uint16_t)(0.32442 * 8192),
(uint16_t)(1.00000 * 8192), (uint16_t)(1.38704 * 8192), (uint16_t)(1.30656 * 8192), (uint16_t)(1.17588 * 8192), (uint16_t)(1.00000 * 8192), (uint16_t)(0.78570 * 8192), (uint16_t)(0.54120 * 8192), (uint16_t)(0.27590 * 8192),
(uint16_t)(0.78570 * 8192), (uint16_t)(1.08979 * 8192), (uint16_t)(1.02656 * 8192), (uint16_t)(0.92388 * 8192), (uint16_t)(0.78570 * 8192), (uint16_t)(0.61732 * 8192), (uint16_t)(0.42522 * 8192), (uint16_t)(0.21677 * 8192),
(uint16_t)(0.54120 * 8192), (uint16_t)(0.75066 * 8192), (uint16_t)(0.70711 * 8192), (uint16_t)(0.63638 * 8192), (uint16_t)(0.54120 * 8192), (uint16_t)(0.42522 * 8192), (uint16_t)(0.29290 * 8192), (uint16_t)(0.14932 * 8192),
(uint16_t)(0.27590 * 8192), (uint16_t)(0.38268 * 8192), (uint16_t)(0.36048 * 8192), (uint16_t)(0.32442 * 8192), (uint16_t)(0.27590 * 8192), (uint16_t)(0.21678 * 8192), (uint16_t)(0.14932 * 8192), (uint16_t)(0.07612 * 8192)
};
/*---------------------------------------------*/
/* Conversion table for fast clipping process */
/*---------------------------------------------*/
#if JD_TBLCLIP
#define BYTECLIP(v) Clip8[(unsigned int)(v) & 0x3FF]
static const uint8_t Clip8[1024] = {
/* 0..255 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
/* 256..511 */
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
/* -512..-257 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* -256..-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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
#else /* JD_TBLCLIP */
static uint8_t BYTECLIP(int val)
{
if(val < 0) return 0;
if(val > 255) return 255;
return (uint8_t)val;
}
#endif
/*-----------------------------------------------------------------------*/
/* Allocate a memory block from memory pool */
/*-----------------------------------------------------------------------*/
static void * alloc_pool( /* Pointer to allocated memory block (NULL:no memory available) */
JDEC * jd, /* Pointer to the decompressor object */
size_t ndata /* Number of bytes to allocate */
)
{
char * rp = 0;
ndata = (ndata + 3) & ~3; /* Align block size to the word boundary */
if(jd->sz_pool >= ndata) {
jd->sz_pool -= ndata;
rp = (char *)jd->pool; /* Get start of available memory pool */
jd->pool = (void *)(rp + ndata); /* Allocate requierd bytes */
}
return (void *)rp; /* Return allocated memory block (NULL:no memory to allocate) */
}
/*-----------------------------------------------------------------------*/
/* Create de-quantization and prescaling tables with a DQT segment */
/*-----------------------------------------------------------------------*/
static JRESULT create_qt_tbl( /* 0:OK, !0:Failed */
JDEC * jd, /* Pointer to the decompressor object */
const uint8_t * data, /* Pointer to the quantizer tables */
size_t ndata /* Size of input data */
)
{
unsigned int i, zi;
uint8_t d;
int32_t * pb;
while(ndata) { /* Process all tables in the segment */
if(ndata < 65) return JDR_FMT1; /* Err: table size is unaligned */
ndata -= 65;
d = *data++; /* Get table property */
if(d & 0xF0) return JDR_FMT1; /* Err: not 8-bit resolution */
i = d & 3; /* Get table ID */
pb = alloc_pool(jd, 64 * sizeof(int32_t)); /* Allocate a memory block for the table */
if(!pb) return JDR_MEM1; /* Err: not enough memory */
jd->qttbl[i] = pb; /* Register the table */
for(i = 0; i < 64; i++) { /* Load the table */
zi = Zig[i]; /* Zigzag-order to raster-order conversion */
pb[zi] = (int32_t)((uint32_t) * data++ * Ipsf[zi]); /* Apply scale factor of Arai algorithm to the de-quantizers */
}
}
return JDR_OK;
}
/*-----------------------------------------------------------------------*/
/* Create huffman code tables with a DHT segment */
/*-----------------------------------------------------------------------*/
static JRESULT create_huffman_tbl( /* 0:OK, !0:Failed */
JDEC * jd, /* Pointer to the decompressor object */
const uint8_t * data, /* Pointer to the packed huffman tables */
size_t ndata /* Size of input data */
)
{
unsigned int i, j, b, cls, num;
size_t np;
uint8_t d, * pb, * pd;
uint16_t hc, * ph;
while(ndata) { /* Process all tables in the segment */
if(ndata < 17) return JDR_FMT1; /* Err: wrong data size */
ndata -= 17;
d = *data++; /* Get table number and class */
if(d & 0xEE) return JDR_FMT1; /* Err: invalid class/number */
cls = d >> 4;
num = d & 0x0F; /* class = dc(0)/ac(1), table number = 0/1 */
pb = alloc_pool(jd, 16); /* Allocate a memory block for the bit distribution table */
if(!pb) return JDR_MEM1; /* Err: not enough memory */
jd->huffbits[num][cls] = pb;
for(np = i = 0; i < 16; i++) { /* Load number of patterns for 1 to 16-bit code */
np += (pb[i] = *data++); /* Get sum of code words for each code */
}
ph = alloc_pool(jd, np * sizeof(uint16_t)); /* Allocate a memory block for the code word table */
if(!ph) return JDR_MEM1; /* Err: not enough memory */
jd->huffcode[num][cls] = ph;
hc = 0;
for(j = i = 0; i < 16; i++) { /* Re-build huffman code word table */
b = pb[i];
while(b--) ph[j++] = hc++;
hc <<= 1;
}
if(ndata < np) return JDR_FMT1; /* Err: wrong data size */
ndata -= np;
pd = alloc_pool(jd, np); /* Allocate a memory block for the decoded data */
if(!pd) return JDR_MEM1; /* Err: not enough memory */
jd->huffdata[num][cls] = pd;
for(i = 0; i < np; i++) { /* Load decoded data corresponds to each code word */
d = *data++;
if(!cls && d > 11) return JDR_FMT1;
pd[i] = d;
}
#if JD_FASTDECODE == 2
{ /* Create fast huffman decode table */
unsigned int span, td, ti;
uint16_t * tbl_ac = 0;
uint8_t * tbl_dc = 0;
if(cls) {
tbl_ac = alloc_pool(jd, HUFF_LEN * sizeof(uint16_t)); /* LUT for AC elements */
if(!tbl_ac) return JDR_MEM1; /* Err: not enough memory */
jd->hufflut_ac[num] = tbl_ac;
memset(tbl_ac, 0xFF, HUFF_LEN * sizeof(uint16_t)); /* Default value (0xFFFF: may be long code) */
}
else {
tbl_dc = alloc_pool(jd, HUFF_LEN * sizeof(uint8_t)); /* LUT for AC elements */
if(!tbl_dc) return JDR_MEM1; /* Err: not enough memory */
jd->hufflut_dc[num] = tbl_dc;
memset(tbl_dc, 0xFF, HUFF_LEN * sizeof(uint8_t)); /* Default value (0xFF: may be long code) */
}
for(i = b = 0; b < HUFF_BIT; b++) { /* Create LUT */
for(j = pb[b]; j; j--) {
ti = ph[i] << (HUFF_BIT - 1 - b) & HUFF_MASK; /* Index of input pattern for the code */
if(cls) {
td = pd[i++] | ((b + 1) << 8); /* b15..b8: code length, b7..b0: zero run and data length */
for(span = 1 << (HUFF_BIT - 1 - b); span; span--, tbl_ac[ti++] = (uint16_t)td) ;
}
else {
td = pd[i++] | ((b + 1) << 4); /* b7..b4: code length, b3..b0: data length */
for(span = 1 << (HUFF_BIT - 1 - b); span; span--, tbl_dc[ti++] = (uint8_t)td) ;
}
}
}
jd->longofs[num][cls] = i; /* Code table offset for long code */
}
#endif
}
return JDR_OK;
}
/*-----------------------------------------------------------------------*/
/* Extract a huffman decoded data from input stream */
/*-----------------------------------------------------------------------*/
static int huffext( /* >=0: decoded data, <0: error code */
JDEC * jd, /* Pointer to the decompressor object */
unsigned int id, /* Table ID (0:Y, 1:C) */
unsigned int cls /* Table class (0:DC, 1:AC) */
)
{
size_t dc = jd->dctr;
uint8_t * dp = jd->dptr;
unsigned int d, flg = 0;
#if JD_FASTDECODE == 0
uint8_t bm, nd, bl;
const uint8_t * hb = jd->huffbits[id][cls]; /* Bit distribution table */
const uint16_t * hc = jd->huffcode[id][cls]; /* Code word table */
const uint8_t * hd = jd->huffdata[id][cls]; /* Data table */
bm = jd->dbit; /* Bit mask to extract */
d = 0;
bl = 16; /* Max code length */
do {
if(!bm) { /* Next byte? */
if(!dc) { /* No input data is available, re-fill input buffer */
dp = jd->inbuf; /* Top of input buffer */
dc = jd->infunc(jd, dp, JD_SZBUF);
if(!dc) return 0 - (int)JDR_INP; /* Err: read error or wrong stream termination */
}
else {
dp++; /* Next data ptr */
}
dc--; /* Decrement number of available bytes */
if(flg) { /* In flag sequence? */
flg = 0; /* Exit flag sequence */
if(*dp != 0) return 0 - (int)JDR_FMT1; /* Err: unexpected flag is detected (may be collapted data) */
*dp = 0xFF; /* The flag is a data 0xFF */
}
else {
if(*dp == 0xFF) { /* Is start of flag sequence? */
flg = 1;
continue; /* Enter flag sequence, get trailing byte */
}
}
bm = 0x80; /* Read from MSB */
}
d <<= 1; /* Get a bit */
if(*dp & bm) d++;
bm >>= 1;
for(nd = *hb++; nd; nd--) { /* Search the code word in this bit length */
if(d == *hc++) { /* Matched? */
jd->dbit = bm;
jd->dctr = dc;
jd->dptr = dp;
return *hd; /* Return the decoded data */
}
hd++;
}
bl--;
} while(bl);
#else
const uint8_t * hb, * hd;
const uint16_t * hc;
unsigned int nc, bl, wbit = jd->dbit % 32;
uint32_t w = jd->wreg & ((1UL << wbit) - 1);
while(wbit < 16) { /* Prepare 16 bits into the working register */
if(jd->marker) {
d = 0xFF; /* Input stream has stalled for a marker. Generate stuff bits */
}
else {
if(!dc) { /* Buffer empty, re-fill input buffer */
dp = jd->inbuf; /* Top of input buffer */
dc = jd->infunc(jd, dp, JD_SZBUF);
if(!dc) return 0 - (int)JDR_INP; /* Err: read error or wrong stream termination */
}
d = *dp++;
dc--;
if(flg) { /* In flag sequence? */
flg = 0; /* Exit flag sequence */
if(d != 0) jd->marker = d; /* Not an escape of 0xFF but a marker */
d = 0xFF;
}
else {
if(d == 0xFF) { /* Is start of flag sequence? */
flg = 1;
continue; /* Enter flag sequence, get trailing byte */
}
}
}
w = w << 8 | d; /* Shift 8 bits in the working register */
wbit += 8;
}
jd->dctr = dc;
jd->dptr = dp;
jd->wreg = w;
#if JD_FASTDECODE == 2
/* Table serch for the short codes */
d = (unsigned int)(w >> (wbit - HUFF_BIT)); /* Short code as table index */
if(cls) { /* AC element */
d = jd->hufflut_ac[id][d]; /* Table decode */
if(d != 0xFFFF) { /* It is done if hit in short code */
jd->dbit = wbit - (d >> 8); /* Snip the code length */
return d & 0xFF; /* b7..0: zero run and following data bits */
}
}
else { /* DC element */
d = jd->hufflut_dc[id][d]; /* Table decode */
if(d != 0xFF) { /* It is done if hit in short code */
jd->dbit = wbit - (d >> 4); /* Snip the code length */
return d & 0xF; /* b3..0: following data bits */
}
}
/* Incremental serch for the codes longer than HUFF_BIT */
hb = jd->huffbits[id][cls] + HUFF_BIT; /* Bit distribution table */
hc = jd->huffcode[id][cls] + jd->longofs[id][cls]; /* Code word table */
hd = jd->huffdata[id][cls] + jd->longofs[id][cls]; /* Data table */
bl = HUFF_BIT + 1;
#else
/* Incremental serch for all codes */
hb = jd->huffbits[id][cls]; /* Bit distribution table */
hc = jd->huffcode[id][cls]; /* Code word table */
hd = jd->huffdata[id][cls]; /* Data table */
bl = 1;
#endif
for(; bl <= 16; bl++) { /* Incremental search */
nc = *hb++;
if(nc) {
d = w >> (wbit - bl);
do { /* Search the code word in this bit length */
if(d == *hc++) { /* Matched? */
jd->dbit = wbit - bl; /* Snip the huffman code */
return *hd; /* Return the decoded data */
}
hd++;
} while(--nc);
}
}
#endif
return 0 - (int)JDR_FMT1; /* Err: code not found (may be collapted data) */
}
/*-----------------------------------------------------------------------*/
/* Extract N bits from input stream */
/*-----------------------------------------------------------------------*/
static int bitext( /* >=0: extracted data, <0: error code */
JDEC * jd, /* Pointer to the decompressor object */
unsigned int nbit /* Number of bits to extract (1 to 16) */
)
{
size_t dc = jd->dctr;
uint8_t * dp = jd->dptr;
unsigned int d, flg = 0;
#if JD_FASTDECODE == 0
uint8_t mbit = jd->dbit;
d = 0;
do {
if(!mbit) { /* Next byte? */
if(!dc) { /* No input data is available, re-fill input buffer */
dp = jd->inbuf; /* Top of input buffer */
dc = jd->infunc(jd, dp, JD_SZBUF);
if(!dc) return 0 - (int)JDR_INP; /* Err: read error or wrong stream termination */
}
else {
dp++; /* Next data ptr */
}
dc--; /* Decrement number of available bytes */
if(flg) { /* In flag sequence? */
flg = 0; /* Exit flag sequence */
if(*dp != 0) return 0 - (int)JDR_FMT1; /* Err: unexpected flag is detected (may be collapted data) */
*dp = 0xFF; /* The flag is a data 0xFF */
}
else {
if(*dp == 0xFF) { /* Is start of flag sequence? */
flg = 1;
continue; /* Enter flag sequence */
}
}
mbit = 0x80; /* Read from MSB */
}
d <<= 1; /* Get a bit */
if(*dp & mbit) d |= 1;
mbit >>= 1;
nbit--;
} while(nbit);
jd->dbit = mbit;
jd->dctr = dc;
jd->dptr = dp;
return (int)d;
#else
unsigned int wbit = jd->dbit % 32;
uint32_t w = jd->wreg & ((1UL << wbit) - 1);
while(wbit < nbit) { /* Prepare nbit bits into the working register */
if(jd->marker) {
d = 0xFF; /* Input stream stalled, generate stuff bits */
}
else {
if(!dc) { /* Buffer empty, re-fill input buffer */
dp = jd->inbuf; /* Top of input buffer */
dc = jd->infunc(jd, dp, JD_SZBUF);
if(!dc) return 0 - (int)JDR_INP; /* Err: read error or wrong stream termination */
}
d = *dp++;
dc--;
if(flg) { /* In flag sequence? */
flg = 0; /* Exit flag sequence */
if(d != 0) jd->marker = d; /* Not an escape of 0xFF but a marker */
d = 0xFF;
}
else {
if(d == 0xFF) { /* Is start of flag sequence? */
flg = 1;
continue; /* Enter flag sequence, get trailing byte */
}
}
}
w = w << 8 | d; /* Get 8 bits into the working register */
wbit += 8;
}
jd->wreg = w;
jd->dbit = wbit - nbit;
jd->dctr = dc;
jd->dptr = dp;
return (int)(w >> ((wbit - nbit) % 32));
#endif
}
/*-----------------------------------------------------------------------*/
/* Process restart interval */
/*-----------------------------------------------------------------------*/
JRESULT jd_restart(
JDEC * jd, /* Pointer to the decompressor object */
uint16_t rstn /* Expected restert sequense number */
)
{
unsigned int i;
uint8_t * dp = jd->dptr;
size_t dc = jd->dctr;
#if JD_FASTDECODE == 0
uint16_t d = 0;
/* Get two bytes from the input stream */
for(i = 0; i < 2; i++) {
if(!dc) { /* No input data is available, re-fill input buffer */
dp = jd->inbuf;
dc = jd->infunc(jd, dp, JD_SZBUF);
if(!dc) return JDR_INP;
}
else {
dp++;
}
dc--;
d = d << 8 | *dp; /* Get a byte */
}
jd->dptr = dp;
jd->dctr = dc;
jd->dbit = 0;
/* Check the marker */
if((d & 0xFFD8) != 0xFFD0 || (d & 7) != (rstn & 7)) {
return JDR_FMT1; /* Err: expected RSTn marker is not detected (may be collapted data) */
}
#else
uint16_t marker;
if(jd->marker) { /* Generate a maker if it has been detected */
marker = 0xFF00 | jd->marker;
jd->marker = 0;
}
else {
marker = 0;
for(i = 0; i < 2; i++) { /* Get a restart marker */
if(!dc) { /* No input data is available, re-fill input buffer */
dp = jd->inbuf;
dc = jd->infunc(jd, dp, JD_SZBUF);
if(!dc) return JDR_INP;
}
marker = (marker << 8) | *dp++; /* Get a byte */
dc--;
}
jd->dptr = dp;
jd->dctr = dc;
}
/* Check the marker */
if((marker & 0xFFD8) != 0xFFD0 || (marker & 7) != (rstn & 7)) {
return JDR_FMT1; /* Err: expected RSTn marker was not detected (may be collapted data) */
}
jd->dbit = 0; /* Discard stuff bits */
#endif
jd->dcv[2] = jd->dcv[1] = jd->dcv[0] = 0; /* Reset DC offset */
return JDR_OK;
}
/*-----------------------------------------------------------------------*/
/* Apply Inverse-DCT in Arai Algorithm (see also aa_idct.png) */
/*-----------------------------------------------------------------------*/
static void block_idct(
int32_t * src, /* Input block data (de-quantized and pre-scaled for Arai Algorithm) */
jd_yuv_t * dst /* Pointer to the destination to store the block as byte array */
)
{
const int32_t M13 = (int32_t)(1.41421 * 4096), M2 = (int32_t)(1.08239 * 4096), M4 = (int32_t)(2.61313 * 4096),
M5 = (int32_t)(1.84776 * 4096);
int32_t v0, v1, v2, v3, v4, v5, v6, v7;
int32_t t10, t11, t12, t13;
int i;
/* Process columns */
for(i = 0; i < 8; i++) {
v0 = src[8 * 0]; /* Get even elements */
v1 = src[8 * 2];
v2 = src[8 * 4];
v3 = src[8 * 6];
t10 = v0 + v2; /* Process the even elements */
t12 = v0 - v2;
t11 = (v1 - v3) * M13 >> 12;
v3 += v1;
t11 -= v3;
v0 = t10 + v3;
v3 = t10 - v3;
v1 = t11 + t12;
v2 = t12 - t11;
v4 = src[8 * 7]; /* Get odd elements */
v5 = src[8 * 1];
v6 = src[8 * 5];
v7 = src[8 * 3];
t10 = v5 - v4; /* Process the odd elements */
t11 = v5 + v4;
t12 = v6 - v7;
v7 += v6;
v5 = (t11 - v7) * M13 >> 12;
v7 += t11;
t13 = (t10 + t12) * M5 >> 12;
v4 = t13 - (t10 * M2 >> 12);
v6 = t13 - (t12 * M4 >> 12) - v7;
v5 -= v6;
v4 -= v5;
src[8 * 0] = v0 + v7; /* Write-back transformed values */
src[8 * 7] = v0 - v7;
src[8 * 1] = v1 + v6;
src[8 * 6] = v1 - v6;
src[8 * 2] = v2 + v5;
src[8 * 5] = v2 - v5;
src[8 * 3] = v3 + v4;
src[8 * 4] = v3 - v4;
src++; /* Next column */
}
/* Process rows */
src -= 8;
for(i = 0; i < 8; i++) {
v0 = src[0] + (128L << 8); /* Get even elements (remove DC offset (-128) here) */
v1 = src[2];
v2 = src[4];
v3 = src[6];
t10 = v0 + v2; /* Process the even elements */
t12 = v0 - v2;
t11 = (v1 - v3) * M13 >> 12;
v3 += v1;
t11 -= v3;
v0 = t10 + v3;
v3 = t10 - v3;
v1 = t11 + t12;
v2 = t12 - t11;
v4 = src[7]; /* Get odd elements */
v5 = src[1];
v6 = src[5];
v7 = src[3];
t10 = v5 - v4; /* Process the odd elements */
t11 = v5 + v4;
t12 = v6 - v7;
v7 += v6;
v5 = (t11 - v7) * M13 >> 12;
v7 += t11;
t13 = (t10 + t12) * M5 >> 12;
v4 = t13 - (t10 * M2 >> 12);
v6 = t13 - (t12 * M4 >> 12) - v7;
v5 -= v6;
v4 -= v5;
/* Descale the transformed values 8 bits and output a row */
#if JD_FASTDECODE >= 1
dst[0] = (int16_t)((v0 + v7) >> 8);
dst[7] = (int16_t)((v0 - v7) >> 8);
dst[1] = (int16_t)((v1 + v6) >> 8);
dst[6] = (int16_t)((v1 - v6) >> 8);
dst[2] = (int16_t)((v2 + v5) >> 8);
dst[5] = (int16_t)((v2 - v5) >> 8);
dst[3] = (int16_t)((v3 + v4) >> 8);
dst[4] = (int16_t)((v3 - v4) >> 8);
#else
dst[0] = BYTECLIP((v0 + v7) >> 8);
dst[7] = BYTECLIP((v0 - v7) >> 8);
dst[1] = BYTECLIP((v1 + v6) >> 8);
dst[6] = BYTECLIP((v1 - v6) >> 8);
dst[2] = BYTECLIP((v2 + v5) >> 8);
dst[5] = BYTECLIP((v2 - v5) >> 8);
dst[3] = BYTECLIP((v3 + v4) >> 8);
dst[4] = BYTECLIP((v3 - v4) >> 8);
#endif
dst += 8;
src += 8; /* Next row */
}
}
/*-----------------------------------------------------------------------*/
/* Load all blocks in an MCU into working buffer */
/*-----------------------------------------------------------------------*/
JRESULT jd_mcu_load(
JDEC * jd /* Pointer to the decompressor object */
)
{
int32_t * tmp = (int32_t *)jd->workbuf; /* Block working buffer for de-quantize and IDCT */
int d, e;
unsigned int blk, nby, i, bc, z, id, cmp;
jd_yuv_t * bp;
const int32_t * dqf;
nby = jd->msx * jd->msy; /* Number of Y blocks (1, 2 or 4) */
bp = jd->mcubuf; /* Pointer to the first block of MCU */
for(blk = 0; blk < nby + 2; blk++) { /* Get nby Y blocks and two C blocks */
cmp = (blk < nby) ? 0 : blk - nby + 1; /* Component number 0:Y, 1:Cb, 2:Cr */
if(cmp && jd->ncomp != 3) { /* Clear C blocks if not exist (monochrome image) */
for(i = 0; i < 64; bp[i++] = 128) ;
}
else { /* Load Y/C blocks from input stream */
id = cmp ? 1 : 0; /* Huffman table ID of this component */
/* Extract a DC element from input stream */
d = huffext(jd, id, 0); /* Extract a huffman coded data (bit length) */
if(d < 0) return (JRESULT)(0 - d); /* Err: invalid code or input */
bc = (unsigned int)d;
d = jd->dcv[cmp]; /* DC value of previous block */
if(bc) { /* If there is any difference from previous block */
e = bitext(jd, bc); /* Extract data bits */
if(e < 0) return (JRESULT)(0 - e); /* Err: input */
bc = 1 << (bc - 1); /* MSB position */
if(!(e & bc)) e -= (bc << 1) - 1; /* Restore negative value if needed */
d += e; /* Get current value */
jd->dcv[cmp] = (int16_t)d; /* Save current DC value for next block */
}
dqf = jd->qttbl[jd->qtid[cmp]]; /* De-quantizer table ID for this component */
tmp[0] = d * dqf[0] >> 8; /* De-quantize, apply scale factor of Arai algorithm and descale 8 bits */
/* Extract following 63 AC elements from input stream */
memset(&tmp[1], 0, 63 * sizeof(int32_t)); /* Initialize all AC elements */
z = 1; /* Top of the AC elements (in zigzag-order) */
do {
d = huffext(jd, id, 1); /* Extract a huffman coded value (zero runs and bit length) */
if(d == 0) break; /* EOB? */
if(d < 0) return (JRESULT)(0 - d); /* Err: invalid code or input error */
bc = (unsigned int)d;
z += bc >> 4; /* Skip leading zero run */
if(z >= 64) return JDR_FMT1; /* Too long zero run */
if(bc &= 0x0F) { /* Bit length? */
d = bitext(jd, bc); /* Extract data bits */
if(d < 0) return (JRESULT)(0 - d); /* Err: input device */
bc = 1 << (bc - 1); /* MSB position */
if(!(d & bc)) d -= (bc << 1) - 1; /* Restore negative value if needed */
i = Zig[z]; /* Get raster-order index */
tmp[i] = d * dqf[i] >> 8; /* De-quantize, apply scale factor of Arai algorithm and descale 8 bits */
}
} while(++z < 64); /* Next AC element */
if(JD_FORMAT != 2 || !cmp) { /* C components may not be processed if in grayscale output */
if(z == 1 || (JD_USE_SCALE &&
jd->scale ==
3)) { /* If no AC element or scale ratio is 1/8, IDCT can be ommited and the block is filled with DC value */
d = (jd_yuv_t)((*tmp / 256) + 128);
if(JD_FASTDECODE >= 1) {
for(i = 0; i < 64; bp[i++] = d) ;
}
else {
memset(bp, d, 64);
}
}
else {
block_idct(tmp, bp); /* Apply IDCT and store the block to the MCU buffer */
}
}
}
bp += 64; /* Next block */
}
return JDR_OK; /* All blocks have been loaded successfully */
}
/*-----------------------------------------------------------------------*/
/* Output an MCU: Convert YCrCb to RGB and output it in RGB form */
/*-----------------------------------------------------------------------*/
JRESULT jd_mcu_output(
JDEC * jd, /* Pointer to the decompressor object */
int (*outfunc)(JDEC *, void *, JRECT *), /* RGB output function */
unsigned int x, /* MCU location in the image */
unsigned int y /* MCU location in the image */
)
{
const int CVACC = (sizeof(int) > 2) ? 1024 : 128; /* Adaptive accuracy for both 16-/32-bit systems */
unsigned int ix, iy, mx, my, rx, ry;
int yy, cb, cr;
jd_yuv_t * py, * pc;
uint8_t * pix;
JRECT rect;
mx = jd->msx * 8;
my = jd->msy * 8; /* MCU size (pixel) */
rx = (x + mx <= jd->width) ? mx : jd->width -
x; /* Output rectangular size (it may be clipped at right/bottom end of image) */
ry = (y + my <= jd->height) ? my : jd->height - y;
if(JD_USE_SCALE) {
rx >>= jd->scale;
ry >>= jd->scale;
if(!rx || !ry) return JDR_OK; /* Skip this MCU if all pixel is to be rounded off */
x >>= jd->scale;
y >>= jd->scale;
}
rect.left = x;
rect.right = x + rx - 1; /* Rectangular area in the frame buffer */
rect.top = y;
rect.bottom = y + ry - 1;
if(!JD_USE_SCALE || jd->scale != 3) { /* Not for 1/8 scaling */
pix = (uint8_t *)jd->workbuf;
if(JD_FORMAT != 2) { /* RGB output (build an RGB MCU from Y/C component) */
for(iy = 0; iy < my; iy++) {
pc = py = jd->mcubuf;
if(my == 16) { /* Double block height? */
pc += 64 * 4 + (iy >> 1) * 8;
if(iy >= 8) py += 64;
}
else { /* Single block height */
pc += mx * 8 + iy * 8;
}
py += iy * 8;
for(ix = 0; ix < mx; ix++) {
cb = pc[0] - 128; /* Get Cb/Cr component and remove offset */
cr = pc[64] - 128;
if(mx == 16) { /* Double block width? */
if(ix == 8) py += 64 - 8; /* Jump to next block if double block heigt */
pc += ix & 1; /* Step forward chroma pointer every two pixels */
}
else { /* Single block width */
pc++; /* Step forward chroma pointer every pixel */
}
yy = *py++; /* Get Y component */
*pix++ = /*B*/ BYTECLIP(yy + ((int)(1.772 * CVACC) * cb) / CVACC);
*pix++ = /*G*/ BYTECLIP(yy - ((int)(0.344 * CVACC) * cb + (int)(0.714 * CVACC) * cr) / CVACC);
*pix++ = /*R*/ BYTECLIP(yy + ((int)(1.402 * CVACC) * cr) / CVACC);
}
}
}
}
/* Squeeze up pixel table if a part of MCU is to be truncated */
mx >>= jd->scale;
if(rx < mx) { /* Is the MCU spans rigit edge? */
uint8_t * s, * d;
unsigned int xi, yi;
s = d = (uint8_t *)jd->workbuf;
for(yi = 0; yi < ry; yi++) {
for(xi = 0; xi < rx; xi++) { /* Copy effective pixels */
*d++ = *s++;
if(JD_FORMAT != 2) {
*d++ = *s++;
*d++ = *s++;
}
}
s += (mx - rx) * (JD_FORMAT != 2 ? 3 : 1); /* Skip truncated pixels */
}
}
/* Convert RGB888 to RGB565 if needed */
if(JD_FORMAT == 1) {
uint8_t * s = (uint8_t *)jd->workbuf;
uint16_t w, * d = (uint16_t *)s;
unsigned int n = rx * ry;
do {
w = (*s++ & 0xF8) << 8; /* RRRRR----------- */
w |= (*s++ & 0xFC) << 3; /* -----GGGGGG----- */
w |= *s++ >> 3; /* -----------BBBBB */
*d++ = w;
} while(--n);
}
/* Output the rectangular */
if(outfunc) return outfunc(jd, jd->workbuf, &rect) ? JDR_OK : JDR_INTR;
return 0;
}
/*-----------------------------------------------------------------------*/
/* Analyze the JPEG image and Initialize decompressor object */
/*-----------------------------------------------------------------------*/
#define LDB_WORD(ptr) (uint16_t)(((uint16_t)*((uint8_t*)(ptr))<<8)|(uint16_t)*(uint8_t*)((ptr)+1))
JRESULT jd_prepare(
JDEC * jd, /* Blank decompressor object */
size_t (*infunc)(JDEC *, uint8_t *, size_t), /* JPEG strem input function */
void * pool, /* Working buffer for the decompression session */
size_t sz_pool, /* Size of working buffer */
void * dev /* I/O device identifier for the session */
)
{
uint8_t * seg, b;
uint16_t marker;
unsigned int n, i, ofs;
size_t len;
JRESULT rc;
memset(jd, 0, sizeof(
JDEC)); /* Clear decompression object (this might be a problem if machine's null pointer is not all bits zero) */
jd->pool = pool; /* Work memroy */
jd->pool_original = pool;
jd->sz_pool = sz_pool; /* Size of given work memory */
jd->infunc = infunc; /* Stream input function */
jd->device = dev; /* I/O device identifier */
jd->inbuf = seg = alloc_pool(jd, JD_SZBUF); /* Allocate stream input buffer */
if(!seg) return JDR_MEM1;
ofs = marker = 0; /* Find SOI marker */
do {
if(jd->infunc(jd, seg, 1) != 1) return JDR_INP; /* Err: SOI was not detected */
ofs++;
marker = marker << 8 | seg[0];
} while(marker != 0xFFD8);
for(;;) { /* Parse JPEG segments */
/* Get a JPEG marker */
if(jd->infunc(jd, seg, 4) != 4) return JDR_INP;
marker = LDB_WORD(seg); /* Marker */
len = LDB_WORD(seg + 2); /* Length field */
if(len <= 2 || (marker >> 8) != 0xFF) return JDR_FMT1;
len -= 2; /* Segent content size */
ofs += 4 + len; /* Number of bytes loaded */
switch(marker & 0xFF) {
case 0xC0: /* SOF0 (baseline JPEG) */
if(len > JD_SZBUF) return JDR_MEM2;
if(jd->infunc(jd, seg, len) != len) return JDR_INP; /* Load segment data */
jd->width = LDB_WORD(&seg[3]); /* Image width in unit of pixel */
jd->height = LDB_WORD(&seg[1]); /* Image height in unit of pixel */
jd->ncomp = seg[5]; /* Number of color components */
if(jd->ncomp != 3 && jd->ncomp != 1) return JDR_FMT3; /* Err: Supports only Grayscale and Y/Cb/Cr */
/* Check each image component */
for(i = 0; i < jd->ncomp; i++) {
b = seg[7 + 3 * i]; /* Get sampling factor */
if(i == 0) { /* Y component */
if(b != 0x11 && b != 0x22 && b != 0x21) { /* Check sampling factor */
return JDR_FMT3; /* Err: Supports only 4:4:4, 4:2:0 or 4:2:2 */
}
jd->msx = b >> 4;
jd->msy = b & 15; /* Size of MCU [blocks] */
}
else { /* Cb/Cr component */
if(b != 0x11) return JDR_FMT3; /* Err: Sampling factor of Cb/Cr must be 1 */
}
jd->qtid[i] = seg[8 + 3 * i]; /* Get dequantizer table ID for this component */
if(jd->qtid[i] > 3) return JDR_FMT3; /* Err: Invalid ID */
}
break;
case 0xDD: /* DRI - Define Restart Interval */
if(len > JD_SZBUF) return JDR_MEM2;
if(jd->infunc(jd, seg, len) != len) return JDR_INP; /* Load segment data */
jd->nrst = LDB_WORD(seg); /* Get restart interval (MCUs) */
break;
case 0xC4: /* DHT - Define Huffman Tables */
if(len > JD_SZBUF) return JDR_MEM2;
if(jd->infunc(jd, seg, len) != len) return JDR_INP; /* Load segment data */
rc = create_huffman_tbl(jd, seg, len); /* Create huffman tables */
if(rc) return rc;
break;
case 0xDB: /* DQT - Define Quaitizer Tables */
if(len > JD_SZBUF) return JDR_MEM2;
if(jd->infunc(jd, seg, len) != len) return JDR_INP; /* Load segment data */
rc = create_qt_tbl(jd, seg, len); /* Create de-quantizer tables */
if(rc) return rc;
break;
case 0xDA: /* SOS - Start of Scan */
if(len > JD_SZBUF) return JDR_MEM2;
if(jd->infunc(jd, seg, len) != len) return JDR_INP; /* Load segment data */
if(!jd->width || !jd->height) return JDR_FMT1; /* Err: Invalid image size */
if(seg[0] != jd->ncomp) return JDR_FMT3; /* Err: Wrong color components */
/* Check if all tables corresponding to each components have been loaded */
for(i = 0; i < jd->ncomp; i++) {
b = seg[2 + 2 * i]; /* Get huffman table ID */
if(b != 0x00 && b != 0x11) return JDR_FMT3; /* Err: Different table number for DC/AC element */
n = i ? 1 : 0; /* Component class */
if(!jd->huffbits[n][0] || !jd->huffbits[n][1]) { /* Check huffman table for this component */
return JDR_FMT1; /* Err: Nnot loaded */
}
if(!jd->qttbl[jd->qtid[i]]) { /* Check dequantizer table for this component */
return JDR_FMT1; /* Err: Not loaded */
}
}
/* Allocate working buffer for MCU and pixel output */
n = jd->msy * jd->msx; /* Number of Y blocks in the MCU */
if(!n) return JDR_FMT1; /* Err: SOF0 has not been loaded */
len = n * 64 * 2 + 64; /* Allocate buffer for IDCT and RGB output */
if(len < 256) len = 256; /* but at least 256 byte is required for IDCT */
jd->workbuf = alloc_pool(jd,
len); /* and it may occupy a part of following MCU working buffer for RGB output */
if(!jd->workbuf) return JDR_MEM1; /* Err: not enough memory */
jd->mcubuf = alloc_pool(jd, (n + 2) * 64 * sizeof(jd_yuv_t)); /* Allocate MCU working buffer */
if(!jd->mcubuf) return JDR_MEM1; /* Err: not enough memory */
/* Align stream read offset to JD_SZBUF */
if(ofs %= JD_SZBUF) {
jd->dctr = jd->infunc(jd, seg + ofs, (size_t)(JD_SZBUF - ofs));
}
jd->dptr = seg + ofs - (JD_FASTDECODE ? 0 : 1);
return JDR_OK; /* Initialization succeeded. Ready to decompress the JPEG image. */
case 0xC1: /* SOF1 */
case 0xC2: /* SOF2 */
case 0xC3: /* SOF3 */
case 0xC5: /* SOF5 */
case 0xC6: /* SOF6 */
case 0xC7: /* SOF7 */
case 0xC9: /* SOF9 */
case 0xCA: /* SOF10 */
case 0xCB: /* SOF11 */
case 0xCD: /* SOF13 */
case 0xCE: /* SOF14 */
case 0xCF: /* SOF15 */
case 0xD9: /* EOI */
return JDR_FMT3; /* Unsuppoted JPEG standard (may be progressive JPEG) */
default: /* Unknown segment (comment, exif or etc..) */
/* Skip segment data (null pointer specifies to remove data from the stream) */
if(jd->infunc(jd, 0, len) != len) return JDR_INP;
}
}
}
/*-----------------------------------------------------------------------*/
/* Start to decompress the JPEG picture */
/*-----------------------------------------------------------------------*/
JRESULT jd_decomp(
JDEC * jd, /* Initialized decompression object */
int (*outfunc)(JDEC *, void *, JRECT *), /* RGB output function */
uint8_t scale /* Output de-scaling factor (0 to 3) */
)
{
unsigned int x, y, mx, my;
uint16_t rst, rsc;
JRESULT rc;
if(scale > (JD_USE_SCALE ? 3 : 0)) return JDR_PAR;
jd->scale = scale;
mx = jd->msx * 8;
my = jd->msy * 8; /* Size of the MCU (pixel) */
jd->dcv[2] = jd->dcv[1] = jd->dcv[0] = 0; /* Initialize DC values */
rst = rsc = 0;
rc = JDR_OK;
for(y = 0; y < jd->height; y += my) { /* Vertical loop of MCUs */
for(x = 0; x < jd->width; x += mx) { /* Horizontal loop of MCUs */
if(jd->nrst && rst++ == jd->nrst) { /* Process restart interval if enabled */
rc = jd_restart(jd, rsc++);
if(rc != JDR_OK) return rc;
rst = 1;
}
rc = jd_mcu_load(jd); /* Load an MCU (decompress huffman coded stream, dequantize and apply IDCT) */
if(rc != JDR_OK) return rc;
rc = jd_mcu_output(jd, outfunc, x, y); /* Output the MCU (YCbCr to RGB, scaling and output) */
if(rc != JDR_OK) return rc;
}
}
return rc;
}
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/tjpgd/tjpgdcnf.h | /*----------------------------------------------*/
/* TJpgDec System Configurations R0.03 */
/*----------------------------------------------*/
#define JD_SZBUF 512
/* Specifies size of stream input buffer */
#define JD_FORMAT 0
/* Specifies output pixel format.
/ 0: RGB888 (24-bit/pix)
/ 1: RGB565 (16-bit/pix)
/ 2: Grayscale (8-bit/pix)
*/
#define JD_USE_SCALE 0
/* Switches output descaling feature.
/ 0: Disable
/ 1: Enable
*/
#define JD_TBLCLIP 1
/* Use table conversion for saturation arithmetic. A bit faster, but increases 1 KB of code size.
/ 0: Disable
/ 1: Enable
*/
#define JD_FASTDECODE 1
/* Optimization level
/ 0: Basic optimization. Suitable for 8/16-bit MCUs.
/ 1: + 32-bit barrel shifter. Suitable for 32-bit MCUs.
/ 2: + Table conversion for huffman decoding (wants 6 << HUFF_BIT bytes of RAM)
*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/tjpgd/lv_tjpgd.h | /**
* @file lv_tjpgd.h
*
*/
#ifndef LV_TJPGD_H
#define LV_TJPGD_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#if LV_USE_TJPGD
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
void lv_tjpgd_init(void);
void lv_tjpgd_deinit(void);
/**********************
* MACROS
**********************/
#endif /*LV_USE_TJPGD*/
#ifdef __cplusplus
}
#endif
#endif /* LV_TJPGD_H */
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/qrcode/lv_qrcode.h | /**
* @file lv_qrcode
*
*/
#ifndef LV_QRCODE_H
#define LV_QRCODE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_QRCODE
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/*Data of qrcode*/
typedef struct {
lv_canvas_t canvas;
lv_color_t dark_color;
lv_color_t light_color;
} lv_qrcode_t;
extern const lv_obj_class_t lv_qrcode_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create an empty QR code (an `lv_canvas`) object.
* @param parent point to an object where to create the QR code
* @return pointer to the created QR code object
*/
lv_obj_t * lv_qrcode_create(lv_obj_t * parent);
/**
* Set QR code size.
* @param obj pointer to a QR code object
* @param size width and height of the QR code
*/
void lv_qrcode_set_size(lv_obj_t * obj, int32_t size);
/**
* Set QR code dark color.
* @param obj pointer to a QR code object
* @param color dark color of the QR code
*/
void lv_qrcode_set_dark_color(lv_obj_t * obj, lv_color_t color);
/**
* Set QR code light color.
* @param obj pointer to a QR code object
* @param color light color of the QR code
*/
void lv_qrcode_set_light_color(lv_obj_t * obj, lv_color_t color);
/**
* Set the data of a QR code object
* @param obj pointer to a QR code object
* @param data data to display
* @param data_len length of data in bytes
* @return LV_RESULT_OK: if no error; LV_RESULT_INVALID: on error
*/
lv_result_t lv_qrcode_update(lv_obj_t * obj, const void * data, uint32_t data_len);
/**********************
* MACROS
**********************/
#endif /*LV_USE_QRCODE*/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*LV_QRCODE_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/qrcode/lv_qrcode.c | /**
* @file lv_qrcode.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_qrcode.h"
#if LV_USE_QRCODE
#include "qrcodegen.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_qrcode_class
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_qrcode_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_qrcode_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_qrcode_class = {
.constructor_cb = lv_qrcode_constructor,
.destructor_cb = lv_qrcode_destructor,
.instance_size = sizeof(lv_qrcode_t),
.base_class = &lv_canvas_class,
.name = "qrcode",
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Create an empty QR code (an `lv_canvas`) object.
* @param parent point to an object where to create the QR code
* @return pointer to the created QR code object
*/
lv_obj_t * lv_qrcode_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;
}
void lv_qrcode_set_size(lv_obj_t * obj, int32_t size)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_image_dsc_t * img_dsc = lv_canvas_get_image(obj);
void * buf = (void *)img_dsc->data;
uint32_t buf_size = LV_CANVAS_BUF_SIZE_INDEXED_1BIT(size, size);
buf = lv_realloc(buf, buf_size);
LV_ASSERT_MALLOC(buf);
if(buf == NULL) {
LV_LOG_ERROR("malloc failed for canvas buffer");
return;
}
lv_canvas_set_buffer(obj, buf, size, size, LV_COLOR_FORMAT_I1);
/*Clear canvas buffer*/
lv_canvas_fill_bg(obj, lv_color_white(), LV_OPA_COVER);
}
void lv_qrcode_set_dark_color(lv_obj_t * obj, lv_color_t color)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_qrcode_t * qrcode = (lv_qrcode_t *)obj;
qrcode->dark_color = color;
}
void lv_qrcode_set_light_color(lv_obj_t * obj, lv_color_t color)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_qrcode_t * qrcode = (lv_qrcode_t *)obj;
qrcode->light_color = color;
}
lv_result_t lv_qrcode_update(lv_obj_t * obj, const void * data, uint32_t data_len)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_qrcode_t * qrcode = (lv_qrcode_t *)obj;
lv_image_dsc_t * img_dsc = lv_canvas_get_image(obj);
if(!img_dsc->data) {
LV_LOG_ERROR("canvas buffer is NULL");
return LV_RESULT_INVALID;
}
lv_canvas_set_palette(obj, 0, lv_color_to_32(qrcode->dark_color, 0xff));
lv_canvas_set_palette(obj, 1, lv_color_to_32(qrcode->light_color, 0xff));
lv_color_t c = lv_color_from_int(1);
lv_canvas_fill_bg(obj, c, LV_OPA_COVER);
if(data_len > qrcodegen_BUFFER_LEN_MAX) return LV_RESULT_INVALID;
int32_t qr_version = qrcodegen_getMinFitVersion(qrcodegen_Ecc_MEDIUM, data_len);
if(qr_version <= 0) return LV_RESULT_INVALID;
int32_t qr_size = qrcodegen_version2size(qr_version);
if(qr_size <= 0) return LV_RESULT_INVALID;
int32_t scale = img_dsc->header.w / qr_size;
if(scale <= 0) return LV_RESULT_INVALID;
int32_t remain = img_dsc->header.w % qr_size;
/* The qr version is incremented by four point */
uint32_t version_extend = remain / (scale << 2);
if(version_extend && qr_version < qrcodegen_VERSION_MAX) {
qr_version = qr_version + version_extend > qrcodegen_VERSION_MAX ?
qrcodegen_VERSION_MAX : qr_version + version_extend;
}
uint8_t * qr0 = lv_malloc(qrcodegen_BUFFER_LEN_FOR_VERSION(qr_version));
LV_ASSERT_MALLOC(qr0);
uint8_t * data_tmp = lv_malloc(qrcodegen_BUFFER_LEN_FOR_VERSION(qr_version));
LV_ASSERT_MALLOC(data_tmp);
lv_memcpy(data_tmp, data, data_len);
bool ok = qrcodegen_encodeBinary(data_tmp, data_len,
qr0, qrcodegen_Ecc_MEDIUM,
qr_version, qr_version,
qrcodegen_Mask_AUTO, true);
if(!ok) {
lv_free(qr0);
lv_free(data_tmp);
return LV_RESULT_INVALID;
}
int32_t obj_w = img_dsc->header.w;
qr_size = qrcodegen_getSize(qr0);
scale = obj_w / qr_size;
int scaled = qr_size * scale;
int margin = (obj_w - scaled) / 2;
uint8_t * buf_u8 = (uint8_t *)img_dsc->data + 8; /*+8 skip the palette*/
/* Copy the qr code canvas:
* A simple `lv_canvas_set_px` would work but it's slow for so many pixels.
* So buffer 1 byte (8 px) from the qr code and set it in the canvas image */
uint32_t row_byte_cnt = (img_dsc->header.w + 7) >> 3;
int y;
for(y = margin; y < scaled + margin; y += scale) {
uint8_t b = 0;
uint8_t p = 0;
bool aligned = false;
int x;
for(x = margin; x < scaled + margin; x++) {
bool a = qrcodegen_getModule(qr0, (x - margin) / scale, (y - margin) / scale);
if(aligned == false && (x & 0x7) == 0) aligned = true;
if(aligned == false) {
c = lv_color_from_int(a ? 0 : 1);
lv_canvas_set_px(obj, x, y, c, LV_OPA_COVER);
}
else {
if(!a) b |= (1 << (7 - p));
p++;
if(p == 8) {
uint32_t px = row_byte_cnt * y + (x >> 3);
buf_u8[px] = b;
b = 0;
p = 0;
}
}
}
/*Process the last byte of the row*/
if(p) {
/*Make the rest of the bits white*/
b |= (1 << (8 - p)) - 1;
uint32_t px = row_byte_cnt * y + (x >> 3);
buf_u8[px] = b;
}
/*The Qr is probably scaled so simply to the repeated rows*/
int s;
const uint8_t * row_ori = buf_u8 + row_byte_cnt * y;
for(s = 1; s < scale; s++) {
lv_memcpy((uint8_t *)buf_u8 + row_byte_cnt * (y + s), row_ori, row_byte_cnt);
}
}
lv_free(qr0);
lv_free(data_tmp);
return LV_RESULT_OK;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_qrcode_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
/*Set default size*/
lv_qrcode_set_size(obj, LV_DPI_DEF);
/*Set default color*/
lv_qrcode_set_dark_color(obj, lv_color_black());
lv_qrcode_set_light_color(obj, lv_color_white());
}
static void lv_qrcode_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_image_dsc_t * img_dsc = lv_canvas_get_image(obj);
lv_cache_lock();
lv_cache_invalidate(lv_cache_find(img_dsc, LV_CACHE_SRC_TYPE_PTR, 0, 0));
lv_cache_unlock();
if(!img_dsc->data) {
return;
}
lv_free((void *)img_dsc->data);
img_dsc->data = NULL;
}
#endif /*LV_USE_QRCODE*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/qrcode/qrcodegen.c | /*
* QR Code generator library (C)
*
* Copyright (c) Project Nayuki. (MIT License)
* https://www.nayuki.io/page/qr-code-generator-library
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* - The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* - The Software is provided "as is", without warranty of any kind, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. In no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the Software or the use or other dealings in the
* Software.
*/
#include <assert.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include "qrcodegen.h"
#ifndef QRCODEGEN_TEST
#define testable static // Keep functions private
#else
#define testable // Expose private functions
#endif
/*---- Forward declarations for private functions ----*/
// Regarding all public and private functions defined in this source file:
// - They require all pointer/array arguments to be not null unless the array length is zero.
// - They only read input scalar/array arguments, write to output pointer/array
// arguments, and return scalar values; they are "pure" functions.
// - They don't read mutable global variables or write to any global variables.
// - They don't perform I/O, read the clock, print to console, etc.
// - They allocate a small and constant amount of stack memory.
// - They don't allocate or free any memory on the heap.
// - They don't recurse or mutually recurse. All the code
// could be inlined into the top-level public functions.
// - They run in at most quadratic time with respect to input arguments.
// Most functions run in linear time, and some in constant time.
// There are no unbounded loops or non-obvious termination conditions.
// - They are completely thread-safe if the caller does not give the
// same writable buffer to concurrent calls to these functions.
testable void appendBitsToBuffer(unsigned int val, int numBits, uint8_t buffer[], int * bitLen);
testable void addEccAndInterleave(uint8_t data[], int version, enum qrcodegen_Ecc ecl, uint8_t result[]);
testable int getNumDataCodewords(int version, enum qrcodegen_Ecc ecl);
testable int getNumRawDataModules(int ver);
testable void calcReedSolomonGenerator(int degree, uint8_t result[]);
testable void calcReedSolomonRemainder(const uint8_t data[], int dataLen,
const uint8_t generator[], int degree, uint8_t result[]);
testable uint8_t finiteFieldMultiply(uint8_t x, uint8_t y);
testable void initializeFunctionModules(int version, uint8_t qrcode[]);
static void drawWhiteFunctionModules(uint8_t qrcode[], int version);
static void drawFormatBits(enum qrcodegen_Ecc ecl, enum qrcodegen_Mask mask, uint8_t qrcode[]);
testable int getAlignmentPatternPositions(int version, uint8_t result[7]);
static void fillRectangle(int left, int top, int width, int height, uint8_t qrcode[]);
static void drawCodewords(const uint8_t data[], int dataLen, uint8_t qrcode[]);
static void applyMask(const uint8_t functionModules[], uint8_t qrcode[], enum qrcodegen_Mask mask);
static long getPenaltyScore(const uint8_t qrcode[]);
static void addRunToHistory(unsigned char run, unsigned char history[7]);
static bool hasFinderLikePattern(const unsigned char runHistory[7]);
testable bool getModule(const uint8_t qrcode[], int x, int y);
testable void setModule(uint8_t qrcode[], int x, int y, bool isBlack);
testable void setModuleBounded(uint8_t qrcode[], int x, int y, bool isBlack);
static bool getBit(int x, int i);
testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars);
testable int getTotalBits(const struct qrcodegen_Segment segs[], size_t len, int version);
static int numCharCountBits(enum qrcodegen_Mode mode, int version);
/*---- Private tables of constants ----*/
// The set of all legal characters in alphanumeric mode, where each character
// value maps to the index in the string. For checking text and encoding segments.
static const char * ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
// For generating error correction codes.
testable const int8_t ECC_CODEWORDS_PER_BLOCK[4][41] = {
// Version: (note that index 0 is for padding, and is set to an illegal value)
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
{-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low
{-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium
{-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile
{-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High
};
#define qrcodegen_REED_SOLOMON_DEGREE_MAX 30 // Based on the table above
// For generating error correction codes.
testable const int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41] = {
// Version: (note that index 0 is for padding, and is set to an illegal value)
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
{-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low
{-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium
{-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile
{-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High
};
// For automatic mask pattern selection.
static const int PENALTY_N1 = 3;
static const int PENALTY_N2 = 3;
static const int PENALTY_N3 = 40;
static const int PENALTY_N4 = 10;
/*---- High-level QR Code encoding functions ----*/
// Public function - see documentation comment in header file.
bool qrcodegen_encodeText(const char * text, uint8_t tempBuffer[], uint8_t qrcode[],
enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl)
{
size_t textLen = strlen(text);
if(textLen == 0)
return qrcodegen_encodeSegmentsAdvanced(NULL, 0, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode);
size_t bufLen = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion);
struct qrcodegen_Segment seg;
if(qrcodegen_isNumeric(text)) {
if(qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_NUMERIC, textLen) > bufLen)
goto fail;
seg = qrcodegen_makeNumeric(text, tempBuffer);
}
else if(qrcodegen_isAlphanumeric(text)) {
if(qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_ALPHANUMERIC, textLen) > bufLen)
goto fail;
seg = qrcodegen_makeAlphanumeric(text, tempBuffer);
}
else {
if(textLen > bufLen)
goto fail;
for(size_t i = 0; i < textLen; i++)
tempBuffer[i] = (uint8_t)text[i];
seg.mode = qrcodegen_Mode_BYTE;
seg.bitLength = calcSegmentBitLength(seg.mode, textLen);
if(seg.bitLength == -1)
goto fail;
seg.numChars = (int)textLen;
seg.data = tempBuffer;
}
return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode);
fail:
qrcode[0] = 0; // Set size to invalid value for safety
return false;
}
// Public function - see documentation comment in header file.
bool qrcodegen_encodeBinary(uint8_t dataAndTemp[], size_t dataLen, uint8_t qrcode[],
enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl)
{
struct qrcodegen_Segment seg;
seg.mode = qrcodegen_Mode_BYTE;
seg.bitLength = calcSegmentBitLength(seg.mode, dataLen);
if(seg.bitLength == -1) {
qrcode[0] = 0; // Set size to invalid value for safety
return false;
}
seg.numChars = (int)dataLen;
seg.data = dataAndTemp;
return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, dataAndTemp, qrcode);
}
// Appends the given number of low-order bits of the given value to the given byte-based
// bit buffer, increasing the bit length. Requires 0 <= numBits <= 16 and val < 2^numBits.
testable void appendBitsToBuffer(unsigned int val, int numBits, uint8_t buffer[], int * bitLen)
{
assert(0 <= numBits && numBits <= 16 && (unsigned long)val >> numBits == 0);
for(int i = numBits - 1; i >= 0; i--, (*bitLen)++)
buffer[*bitLen >> 3] |= ((val >> i) & 1) << (7 - (*bitLen & 7));
}
/*---- Low-level QR Code encoding functions ----*/
// Public function - see documentation comment in header file.
bool qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[], size_t len,
enum qrcodegen_Ecc ecl, uint8_t tempBuffer[], uint8_t qrcode[])
{
return qrcodegen_encodeSegmentsAdvanced(segs, len, ecl,
qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, -1, true, tempBuffer, qrcode);
}
// Public function - see documentation comment in header file.
bool qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[], size_t len, enum qrcodegen_Ecc ecl,
int minVersion, int maxVersion, int mask, bool boostEcl, uint8_t tempBuffer[], uint8_t qrcode[])
{
assert(segs != NULL || len == 0);
assert(qrcodegen_VERSION_MIN <= minVersion && minVersion <= maxVersion && maxVersion <= qrcodegen_VERSION_MAX);
assert(0 <= (int)ecl && (int)ecl <= 3 && -1 <= (int)mask && (int)mask <= 7);
// Find the minimal version number to use
int version, dataUsedBits;
for(version = minVersion; ; version++) {
int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available
dataUsedBits = getTotalBits(segs, len, version);
if(dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
break; // This version number is found to be suitable
if(version >= maxVersion) { // All versions in the range could not fit the given data
qrcode[0] = 0; // Set size to invalid value for safety
return false;
}
}
assert(dataUsedBits != -1);
// Increase the error correction level while the data still fits in the current version number
for(int i = (int)qrcodegen_Ecc_MEDIUM; i <= (int)qrcodegen_Ecc_HIGH; i++) { // From low to high
if(boostEcl && dataUsedBits <= getNumDataCodewords(version, (enum qrcodegen_Ecc)i) * 8)
ecl = (enum qrcodegen_Ecc)i;
}
// Concatenate all segments to create the data bit string
memset(qrcode, 0, qrcodegen_BUFFER_LEN_FOR_VERSION(version) * sizeof(qrcode[0]));
int bitLen = 0;
for(size_t i = 0; i < len; i++) {
const struct qrcodegen_Segment * seg = &segs[i];
appendBitsToBuffer((int)seg->mode, 4, qrcode, &bitLen);
appendBitsToBuffer(seg->numChars, numCharCountBits(seg->mode, version), qrcode, &bitLen);
for(int j = 0; j < seg->bitLength; j++)
appendBitsToBuffer((seg->data[j >> 3] >> (7 - (j & 7))) & 1, 1, qrcode, &bitLen);
}
assert(bitLen == dataUsedBits);
// Add terminator and pad up to a byte if applicable
int dataCapacityBits = getNumDataCodewords(version, ecl) * 8;
assert(bitLen <= dataCapacityBits);
int terminatorBits = dataCapacityBits - bitLen;
if(terminatorBits > 4)
terminatorBits = 4;
appendBitsToBuffer(0, terminatorBits, qrcode, &bitLen);
appendBitsToBuffer(0, (8 - bitLen % 8) % 8, qrcode, &bitLen);
assert(bitLen % 8 == 0);
// Pad with alternating bytes until data capacity is reached
for(uint8_t padByte = 0xEC; bitLen < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
appendBitsToBuffer(padByte, 8, qrcode, &bitLen);
// Draw function and data codeword modules
addEccAndInterleave(qrcode, version, ecl, tempBuffer);
initializeFunctionModules(version, qrcode);
drawCodewords(tempBuffer, getNumRawDataModules(version) / 8, qrcode);
drawWhiteFunctionModules(qrcode, version);
initializeFunctionModules(version, tempBuffer);
// Handle masking
if(mask == qrcodegen_Mask_AUTO) { // Automatically choose best mask
long minPenalty = LONG_MAX;
for(int i = 0; i < 8; i++) {
enum qrcodegen_Mask msk = (enum qrcodegen_Mask)i;
applyMask(tempBuffer, qrcode, msk);
drawFormatBits(ecl, msk, qrcode);
long penalty = getPenaltyScore(qrcode);
if(penalty < minPenalty) {
mask = msk;
minPenalty = penalty;
}
applyMask(tempBuffer, qrcode, msk); // Undoes the mask due to XOR
}
}
assert(0 <= (int)mask && (int)mask <= 7);
applyMask(tempBuffer, qrcode, mask);
drawFormatBits(ecl, mask, qrcode);
return true;
}
/*---- Error correction code generation functions ----*/
// Appends error correction bytes to each block of the given data array, then interleaves
// bytes from the blocks and stores them in the result array. data[0 : dataLen] contains
// the input data. data[dataLen : rawCodewords] is used as a temporary work area and will
// be clobbered by this function. The final answer is stored in result[0 : rawCodewords].
testable void addEccAndInterleave(uint8_t data[], int version, enum qrcodegen_Ecc ecl, uint8_t result[])
{
// Calculate parameter numbers
assert(0 <= (int)ecl && (int)ecl < 4 && qrcodegen_VERSION_MIN <= version && version <= qrcodegen_VERSION_MAX);
int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[(int)ecl][version];
int blockEccLen = ECC_CODEWORDS_PER_BLOCK [(int)ecl][version];
int rawCodewords = getNumRawDataModules(version) / 8;
int dataLen = getNumDataCodewords(version, ecl);
int numShortBlocks = numBlocks - rawCodewords % numBlocks;
int shortBlockDataLen = rawCodewords / numBlocks - blockEccLen;
// Split data into blocks, calculate ECC, and interleave
// (not concatenate) the bytes into a single sequence
uint8_t generator[qrcodegen_REED_SOLOMON_DEGREE_MAX];
calcReedSolomonGenerator(blockEccLen, generator);
const uint8_t * dat = data;
for(int i = 0; i < numBlocks; i++) {
int datLen = shortBlockDataLen + (i < numShortBlocks ? 0 : 1);
uint8_t * ecc = &data[dataLen]; // Temporary storage
calcReedSolomonRemainder(dat, datLen, generator, blockEccLen, ecc);
for(int j = 0, k = i; j < datLen; j++, k += numBlocks) { // Copy data
if(j == shortBlockDataLen)
k -= numShortBlocks;
result[k] = dat[j];
}
for(int j = 0, k = dataLen + i; j < blockEccLen; j++, k += numBlocks) // Copy ECC
result[k] = ecc[j];
dat += datLen;
}
}
// Returns the number of 8-bit codewords that can be used for storing data (not ECC),
// for the given version number and error correction level. The result is in the range [9, 2956].
testable int getNumDataCodewords(int version, enum qrcodegen_Ecc ecl)
{
int v = version, e = (int)ecl;
assert(0 <= e && e < 4);
return getNumRawDataModules(v) / 8
- ECC_CODEWORDS_PER_BLOCK [e][v]
* NUM_ERROR_CORRECTION_BLOCKS[e][v];
}
// Returns the number of data bits that can be stored in a QR Code of the given version number, after
// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
// The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
testable int getNumRawDataModules(int ver)
{
assert(qrcodegen_VERSION_MIN <= ver && ver <= qrcodegen_VERSION_MAX);
int result = (16 * ver + 128) * ver + 64;
if(ver >= 2) {
int numAlign = ver / 7 + 2;
result -= (25 * numAlign - 10) * numAlign - 55;
if(ver >= 7)
result -= 36;
}
return result;
}
/*---- Reed-Solomon ECC generator functions ----*/
// Calculates the Reed-Solomon generator polynomial of the given degree, storing in result[0 : degree].
testable void calcReedSolomonGenerator(int degree, uint8_t result[])
{
// Start with the monomial x^0
assert(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX);
memset(result, 0, degree * sizeof(result[0]));
result[degree - 1] = 1;
// Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
// drop the highest term, and store the rest of the coefficients in order of descending powers.
// Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
uint8_t root = 1;
for(int i = 0; i < degree; i++) {
// Multiply the current product by (x - r^i)
for(int j = 0; j < degree; j++) {
result[j] = finiteFieldMultiply(result[j], root);
if(j + 1 < degree)
result[j] ^= result[j + 1];
}
root = finiteFieldMultiply(root, 0x02);
}
}
// Calculates the remainder of the polynomial data[0 : dataLen] when divided by the generator[0 : degree], where all
// polynomials are in big endian and the generator has an implicit leading 1 term, storing the result in result[0 : degree].
testable void calcReedSolomonRemainder(const uint8_t data[], int dataLen,
const uint8_t generator[], int degree, uint8_t result[])
{
// Perform polynomial division
assert(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX);
memset(result, 0, degree * sizeof(result[0]));
for(int i = 0; i < dataLen; i++) {
uint8_t factor = data[i] ^ result[0];
memmove(&result[0], &result[1], (degree - 1) * sizeof(result[0]));
result[degree - 1] = 0;
for(int j = 0; j < degree; j++)
result[j] ^= finiteFieldMultiply(generator[j], factor);
}
}
#undef qrcodegen_REED_SOLOMON_DEGREE_MAX
// Returns the product of the two given field elements modulo GF(2^8/0x11D).
// All inputs are valid. This could be implemented as a 256*256 lookup table.
testable uint8_t finiteFieldMultiply(uint8_t x, uint8_t y)
{
// Russian peasant multiplication
uint8_t z = 0;
for(int i = 7; i >= 0; i--) {
z = (z << 1) ^ ((z >> 7) * 0x11D);
z ^= ((y >> i) & 1) * x;
}
return z;
}
/*---- Drawing function modules ----*/
// Clears the given QR Code grid with white modules for the given
// version's size, then marks every function module as black.
testable void initializeFunctionModules(int version, uint8_t qrcode[])
{
// Initialize QR Code
int qrsize = version * 4 + 17;
memset(qrcode, 0, ((qrsize * qrsize + 7) / 8 + 1) * sizeof(qrcode[0]));
qrcode[0] = (uint8_t)qrsize;
// Fill horizontal and vertical timing patterns
fillRectangle(6, 0, 1, qrsize, qrcode);
fillRectangle(0, 6, qrsize, 1, qrcode);
// Fill 3 finder patterns (all corners except bottom right) and format bits
fillRectangle(0, 0, 9, 9, qrcode);
fillRectangle(qrsize - 8, 0, 8, 9, qrcode);
fillRectangle(0, qrsize - 8, 9, 8, qrcode);
// Fill numerous alignment patterns
uint8_t alignPatPos[7];
int numAlign = getAlignmentPatternPositions(version, alignPatPos);
for(int i = 0; i < numAlign; i++) {
for(int j = 0; j < numAlign; j++) {
// Don't draw on the three finder corners
if(!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)))
fillRectangle(alignPatPos[i] - 2, alignPatPos[j] - 2, 5, 5, qrcode);
}
}
// Fill version blocks
if(version >= 7) {
fillRectangle(qrsize - 11, 0, 3, 6, qrcode);
fillRectangle(0, qrsize - 11, 6, 3, qrcode);
}
}
// Draws white function modules and possibly some black modules onto the given QR Code, without changing
// non-function modules. This does not draw the format bits. This requires all function modules to be previously
// marked black (namely by initializeFunctionModules()), because this may skip redrawing black function modules.
static void drawWhiteFunctionModules(uint8_t qrcode[], int version)
{
// Draw horizontal and vertical timing patterns
int qrsize = qrcodegen_getSize(qrcode);
for(int i = 7; i < qrsize - 7; i += 2) {
setModule(qrcode, 6, i, false);
setModule(qrcode, i, 6, false);
}
// Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
for(int dy = -4; dy <= 4; dy++) {
for(int dx = -4; dx <= 4; dx++) {
int dist = abs(dx);
if(abs(dy) > dist)
dist = abs(dy);
if(dist == 2 || dist == 4) {
setModuleBounded(qrcode, 3 + dx, 3 + dy, false);
setModuleBounded(qrcode, qrsize - 4 + dx, 3 + dy, false);
setModuleBounded(qrcode, 3 + dx, qrsize - 4 + dy, false);
}
}
}
// Draw numerous alignment patterns
uint8_t alignPatPos[7];
int numAlign = getAlignmentPatternPositions(version, alignPatPos);
for(int i = 0; i < numAlign; i++) {
for(int j = 0; j < numAlign; j++) {
if((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))
continue; // Don't draw on the three finder corners
for(int dy = -1; dy <= 1; dy++) {
for(int dx = -1; dx <= 1; dx++)
setModule(qrcode, alignPatPos[i] + dx, alignPatPos[j] + dy, dx == 0 && dy == 0);
}
}
}
// Draw version blocks
if(version >= 7) {
// Calculate error correction code and pack bits
int rem = version; // version is uint6, in the range [7, 40]
for(int i = 0; i < 12; i++)
rem = (rem << 1) ^ ((rem >> 11) * 0x1F25);
long bits = (long)version << 12 | rem; // uint18
assert(bits >> 18 == 0);
// Draw two copies
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 3; j++) {
int k = qrsize - 11 + j;
setModule(qrcode, k, i, (bits & 1) != 0);
setModule(qrcode, i, k, (bits & 1) != 0);
bits >>= 1;
}
}
}
}
// Draws two copies of the format bits (with its own error correction code) based
// on the given mask and error correction level. This always draws all modules of
// the format bits, unlike drawWhiteFunctionModules() which might skip black modules.
static void drawFormatBits(enum qrcodegen_Ecc ecl, enum qrcodegen_Mask mask, uint8_t qrcode[])
{
// Calculate error correction code and pack bits
assert(0 <= (int)mask && (int)mask <= 7);
static const int table[] = {1, 0, 3, 2};
int data = table[(int)ecl] << 3 | (int)mask; // errCorrLvl is uint2, mask is uint3
int rem = data;
for(int i = 0; i < 10; i++)
rem = (rem << 1) ^ ((rem >> 9) * 0x537);
int bits = (data << 10 | rem) ^ 0x5412; // uint15
assert(bits >> 15 == 0);
// Draw first copy
for(int i = 0; i <= 5; i++)
setModule(qrcode, 8, i, getBit(bits, i));
setModule(qrcode, 8, 7, getBit(bits, 6));
setModule(qrcode, 8, 8, getBit(bits, 7));
setModule(qrcode, 7, 8, getBit(bits, 8));
for(int i = 9; i < 15; i++)
setModule(qrcode, 14 - i, 8, getBit(bits, i));
// Draw second copy
int qrsize = qrcodegen_getSize(qrcode);
for(int i = 0; i < 8; i++)
setModule(qrcode, qrsize - 1 - i, 8, getBit(bits, i));
for(int i = 8; i < 15; i++)
setModule(qrcode, 8, qrsize - 15 + i, getBit(bits, i));
setModule(qrcode, 8, qrsize - 8, true); // Always black
}
// Calculates and stores an ascending list of positions of alignment patterns
// for this version number, returning the length of the list (in the range [0,7]).
// Each position is in the range [0,177), and are used on both the x and y axes.
// This could be implemented as lookup table of 40 variable-length lists of unsigned bytes.
testable int getAlignmentPatternPositions(int version, uint8_t result[7])
{
if(version == 1)
return 0;
int numAlign = version / 7 + 2;
int step = (version == 32) ? 26 :
(version * 4 + numAlign * 2 + 1) / (numAlign * 2 - 2) * 2;
for(int i = numAlign - 1, pos = version * 4 + 10; i >= 1; i--, pos -= step)
result[i] = pos;
result[0] = 6;
return numAlign;
}
// Sets every pixel in the range [left : left + width] * [top : top + height] to black.
static void fillRectangle(int left, int top, int width, int height, uint8_t qrcode[])
{
for(int dy = 0; dy < height; dy++) {
for(int dx = 0; dx < width; dx++)
setModule(qrcode, left + dx, top + dy, true);
}
}
/*---- Drawing data modules and masking ----*/
// Draws the raw codewords (including data and ECC) onto the given QR Code. This requires the initial state of
// the QR Code to be black at function modules and white at codeword modules (including unused remainder bits).
static void drawCodewords(const uint8_t data[], int dataLen, uint8_t qrcode[])
{
int qrsize = qrcodegen_getSize(qrcode);
int i = 0; // Bit index into the data
// Do the funny zigzag scan
for(int right = qrsize - 1; right >= 1; right -= 2) { // Index of right column in each column pair
if(right == 6)
right = 5;
for(int vert = 0; vert < qrsize; vert++) { // Vertical counter
for(int j = 0; j < 2; j++) {
int x = right - j; // Actual x coordinate
bool upward = ((right + 1) & 2) == 0;
int y = upward ? qrsize - 1 - vert : vert; // Actual y coordinate
if(!getModule(qrcode, x, y) && i < dataLen * 8) {
bool black = getBit(data[i >> 3], 7 - (i & 7));
setModule(qrcode, x, y, black);
i++;
}
// If this QR Code has any remainder bits (0 to 7), they were assigned as
// 0/false/white by the constructor and are left unchanged by this method
}
}
}
assert(i == dataLen * 8);
}
// XORs the codeword modules in this QR Code with the given mask pattern.
// The function modules must be marked and the codeword bits must be drawn
// before masking. Due to the arithmetic of XOR, calling applyMask() with
// the same mask value a second time will undo the mask. A final well-formed
// QR Code needs exactly one (not zero, two, etc.) mask applied.
static void applyMask(const uint8_t functionModules[], uint8_t qrcode[], enum qrcodegen_Mask mask)
{
assert(0 <= (int)mask && (int)mask <= 7); // Disallows qrcodegen_Mask_AUTO
int qrsize = qrcodegen_getSize(qrcode);
for(int y = 0; y < qrsize; y++) {
for(int x = 0; x < qrsize; x++) {
if(getModule(functionModules, x, y))
continue;
bool invert;
switch((int)mask) {
case 0:
invert = (x + y) % 2 == 0;
break;
case 1:
invert = y % 2 == 0;
break;
case 2:
invert = x % 3 == 0;
break;
case 3:
invert = (x + y) % 3 == 0;
break;
case 4:
invert = (x / 3 + y / 2) % 2 == 0;
break;
case 5:
invert = x * y % 2 + x * y % 3 == 0;
break;
case 6:
invert = (x * y % 2 + x * y % 3) % 2 == 0;
break;
case 7:
invert = ((x + y) % 2 + x * y % 3) % 2 == 0;
break;
default:
assert(false);
return;
}
bool val = getModule(qrcode, x, y);
setModule(qrcode, x, y, val ^ invert);
}
}
}
// Calculates and returns the penalty score based on state of the given QR Code's current modules.
// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
static long getPenaltyScore(const uint8_t qrcode[])
{
int qrsize = qrcodegen_getSize(qrcode);
long result = 0;
// Adjacent modules in row having same color, and finder-like patterns
for(int y = 0; y < qrsize; y++) {
unsigned char runHistory[7] = {0};
bool color = false;
unsigned char runX = 0;
for(int x = 0; x < qrsize; x++) {
if(getModule(qrcode, x, y) == color) {
runX++;
if(runX == 5)
result += PENALTY_N1;
else if(runX > 5)
result++;
}
else {
addRunToHistory(runX, runHistory);
if(!color && hasFinderLikePattern(runHistory))
result += PENALTY_N3;
color = getModule(qrcode, x, y);
runX = 1;
}
}
addRunToHistory(runX, runHistory);
if(color)
addRunToHistory(0, runHistory); // Dummy run of white
if(hasFinderLikePattern(runHistory))
result += PENALTY_N3;
}
// Adjacent modules in column having same color, and finder-like patterns
for(int x = 0; x < qrsize; x++) {
unsigned char runHistory[7] = {0};
bool color = false;
unsigned char runY = 0;
for(int y = 0; y < qrsize; y++) {
if(getModule(qrcode, x, y) == color) {
runY++;
if(runY == 5)
result += PENALTY_N1;
else if(runY > 5)
result++;
}
else {
addRunToHistory(runY, runHistory);
if(!color && hasFinderLikePattern(runHistory))
result += PENALTY_N3;
color = getModule(qrcode, x, y);
runY = 1;
}
}
addRunToHistory(runY, runHistory);
if(color)
addRunToHistory(0, runHistory); // Dummy run of white
if(hasFinderLikePattern(runHistory))
result += PENALTY_N3;
}
// 2*2 blocks of modules having same color
for(int y = 0; y < qrsize - 1; y++) {
for(int x = 0; x < qrsize - 1; x++) {
bool color = getModule(qrcode, x, y);
if(color == getModule(qrcode, x + 1, y) &&
color == getModule(qrcode, x, y + 1) &&
color == getModule(qrcode, x + 1, y + 1))
result += PENALTY_N2;
}
}
// Balance of black and white modules
int black = 0;
for(int y = 0; y < qrsize; y++) {
for(int x = 0; x < qrsize; x++) {
if(getModule(qrcode, x, y))
black++;
}
}
int total = qrsize * qrsize; // Note that size is odd, so black/total != 1/2
// Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)%
int k = (int)((labs(black * 20L - total * 10L) + total - 1) / total) - 1;
result += k * PENALTY_N4;
return result;
}
// Inserts the given value to the front of the given array, which shifts over the
// existing values and deletes the last value. A helper function for getPenaltyScore().
static void addRunToHistory(unsigned char run, unsigned char history[7])
{
memmove(&history[1], &history[0], 6 * sizeof(history[0]));
history[0] = run;
}
// Tests whether the given run history has the pattern of ratio 1:1:3:1:1 in the middle, and
// surrounded by at least 4 on either or both ends. A helper function for getPenaltyScore().
// Must only be called immediately after a run of white modules has ended.
static bool hasFinderLikePattern(const unsigned char runHistory[7])
{
unsigned char n = runHistory[1];
// The maximum QR Code size is 177, hence the run length n <= 177.
// Arithmetic is promoted to int, so n*4 will not overflow.
return n > 0 && runHistory[2] == n && runHistory[4] == n && runHistory[5] == n
&& runHistory[3] == n * 3 && (runHistory[0] >= n * 4 || runHistory[6] >= n * 4);
}
/*---- Basic QR Code information ----*/
// Public function - see documentation comment in header file.
int qrcodegen_getSize(const uint8_t qrcode[])
{
assert(qrcode != NULL);
int result = qrcode[0];
assert((qrcodegen_VERSION_MIN * 4 + 17) <= result
&& result <= (qrcodegen_VERSION_MAX * 4 + 17));
return result;
}
// Public function - see documentation comment in header file.
bool qrcodegen_getModule(const uint8_t qrcode[], int x, int y)
{
assert(qrcode != NULL);
int qrsize = qrcode[0];
return (0 <= x && x < qrsize && 0 <= y && y < qrsize) && getModule(qrcode, x, y);
}
// Gets the module at the given coordinates, which must be in bounds.
testable bool getModule(const uint8_t qrcode[], int x, int y)
{
int qrsize = qrcode[0];
assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize);
int index = y * qrsize + x;
return getBit(qrcode[(index >> 3) + 1], index & 7);
}
// Sets the module at the given coordinates, which must be in bounds.
testable void setModule(uint8_t qrcode[], int x, int y, bool isBlack)
{
int qrsize = qrcode[0];
assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize);
int index = y * qrsize + x;
int bitIndex = index & 7;
int byteIndex = (index >> 3) + 1;
if(isBlack)
qrcode[byteIndex] |= 1 << bitIndex;
else
qrcode[byteIndex] &= (1 << bitIndex) ^ 0xFF;
}
// Sets the module at the given coordinates, doing nothing if out of bounds.
testable void setModuleBounded(uint8_t qrcode[], int x, int y, bool isBlack)
{
int qrsize = qrcode[0];
if(0 <= x && x < qrsize && 0 <= y && y < qrsize)
setModule(qrcode, x, y, isBlack);
}
// Returns true iff the i'th bit of x is set to 1. Requires x >= 0 and 0 <= i <= 14.
static bool getBit(int x, int i)
{
return ((x >> i) & 1) != 0;
}
/*---- Segment handling ----*/
// Public function - see documentation comment in header file.
bool qrcodegen_isAlphanumeric(const char * text)
{
assert(text != NULL);
for(; *text != '\0'; text++) {
if(strchr(ALPHANUMERIC_CHARSET, *text) == NULL)
return false;
}
return true;
}
// Public function - see documentation comment in header file.
bool qrcodegen_isNumeric(const char * text)
{
assert(text != NULL);
for(; *text != '\0'; text++) {
if(*text < '0' || *text > '9')
return false;
}
return true;
}
// Public function - see documentation comment in header file.
size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars)
{
int temp = calcSegmentBitLength(mode, numChars);
if(temp == -1)
return SIZE_MAX;
assert(0 <= temp && temp <= INT16_MAX);
return ((size_t)temp + 7) / 8;
}
// Returns the number of data bits needed to represent a segment
// containing the given number of characters using the given mode. Notes:
// - Returns -1 on failure, i.e. numChars > INT16_MAX or
// the number of needed bits exceeds INT16_MAX (i.e. 32767).
// - Otherwise, all valid results are in the range [0, INT16_MAX].
// - For byte mode, numChars measures the number of bytes, not Unicode code points.
// - For ECI mode, numChars must be 0, and the worst-case number of bits is returned.
// An actual ECI segment can have shorter data. For non-ECI modes, the result is exact.
testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars)
{
// All calculations are designed to avoid overflow on all platforms
if(numChars > (unsigned int)INT16_MAX)
return -1;
long result = (long)numChars;
if(mode == qrcodegen_Mode_NUMERIC)
result = (result * 10 + 2) / 3; // ceil(10/3 * n)
else if(mode == qrcodegen_Mode_ALPHANUMERIC)
result = (result * 11 + 1) / 2; // ceil(11/2 * n)
else if(mode == qrcodegen_Mode_BYTE)
result *= 8;
else if(mode == qrcodegen_Mode_KANJI)
result *= 13;
else if(mode == qrcodegen_Mode_ECI && numChars == 0)
result = 3 * 8;
else { // Invalid argument
assert(false);
return -1;
}
assert(result >= 0);
if((unsigned int)result > (unsigned int)INT16_MAX)
return -1;
return (int)result;
}
// Public function - see documentation comment in header file.
struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[])
{
assert(data != NULL || len == 0);
struct qrcodegen_Segment result;
result.mode = qrcodegen_Mode_BYTE;
result.bitLength = calcSegmentBitLength(result.mode, len);
assert(result.bitLength != -1);
result.numChars = (int)len;
if(len > 0)
memcpy(buf, data, len * sizeof(buf[0]));
result.data = buf;
return result;
}
// Public function - see documentation comment in header file.
struct qrcodegen_Segment qrcodegen_makeNumeric(const char * digits, uint8_t buf[])
{
assert(digits != NULL);
struct qrcodegen_Segment result;
size_t len = strlen(digits);
result.mode = qrcodegen_Mode_NUMERIC;
int bitLen = calcSegmentBitLength(result.mode, len);
assert(bitLen != -1);
result.numChars = (int)len;
if(bitLen > 0)
memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0]));
result.bitLength = 0;
unsigned int accumData = 0;
int accumCount = 0;
for(; *digits != '\0'; digits++) {
char c = *digits;
assert('0' <= c && c <= '9');
accumData = accumData * 10 + (unsigned int)(c - '0');
accumCount++;
if(accumCount == 3) {
appendBitsToBuffer(accumData, 10, buf, &result.bitLength);
accumData = 0;
accumCount = 0;
}
}
if(accumCount > 0) // 1 or 2 digits remaining
appendBitsToBuffer(accumData, accumCount * 3 + 1, buf, &result.bitLength);
assert(result.bitLength == bitLen);
result.data = buf;
return result;
}
// Public function - see documentation comment in header file.
struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char * text, uint8_t buf[])
{
assert(text != NULL);
struct qrcodegen_Segment result;
size_t len = strlen(text);
result.mode = qrcodegen_Mode_ALPHANUMERIC;
int bitLen = calcSegmentBitLength(result.mode, len);
assert(bitLen != -1);
result.numChars = (int)len;
if(bitLen > 0)
memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0]));
result.bitLength = 0;
unsigned int accumData = 0;
int accumCount = 0;
for(; *text != '\0'; text++) {
const char * temp = strchr(ALPHANUMERIC_CHARSET, *text);
assert(temp != NULL);
accumData = accumData * 45 + (unsigned int)(temp - ALPHANUMERIC_CHARSET);
accumCount++;
if(accumCount == 2) {
appendBitsToBuffer(accumData, 11, buf, &result.bitLength);
accumData = 0;
accumCount = 0;
}
}
if(accumCount > 0) // 1 character remaining
appendBitsToBuffer(accumData, 6, buf, &result.bitLength);
assert(result.bitLength == bitLen);
result.data = buf;
return result;
}
// Public function - see documentation comment in header file.
struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[])
{
struct qrcodegen_Segment result;
result.mode = qrcodegen_Mode_ECI;
result.numChars = 0;
result.bitLength = 0;
if(assignVal < 0) {
assert(false);
}
else if(assignVal < (1 << 7)) {
memset(buf, 0, 1 * sizeof(buf[0]));
appendBitsToBuffer(assignVal, 8, buf, &result.bitLength);
}
else if(assignVal < (1 << 14)) {
memset(buf, 0, 2 * sizeof(buf[0]));
appendBitsToBuffer(2, 2, buf, &result.bitLength);
appendBitsToBuffer(assignVal, 14, buf, &result.bitLength);
}
else if(assignVal < 1000000L) {
memset(buf, 0, 3 * sizeof(buf[0]));
appendBitsToBuffer(6, 3, buf, &result.bitLength);
appendBitsToBuffer(assignVal >> 10, 11, buf, &result.bitLength);
appendBitsToBuffer(assignVal & 0x3FF, 10, buf, &result.bitLength);
}
else {
assert(false);
}
result.data = buf;
return result;
}
// Calculates the number of bits needed to encode the given segments at the given version.
// Returns a non-negative number if successful. Otherwise returns -1 if a segment has too
// many characters to fit its length field, or the total bits exceeds INT16_MAX.
testable int getTotalBits(const struct qrcodegen_Segment segs[], size_t len, int version)
{
assert(segs != NULL || len == 0);
long result = 0;
for(size_t i = 0; i < len; i++) {
int numChars = segs[i].numChars;
int bitLength = segs[i].bitLength;
assert(0 <= numChars && numChars <= INT16_MAX);
assert(0 <= bitLength && bitLength <= INT16_MAX);
int ccbits = numCharCountBits(segs[i].mode, version);
assert(0 <= ccbits && ccbits <= 16);
if(numChars >= (1L << ccbits))
return -1; // The segment's length doesn't fit the field's bit width
result += 4L + ccbits + bitLength;
if(result > INT16_MAX)
return -1; // The sum might overflow an int type
}
assert(0 <= result && result <= INT16_MAX);
return (int)result;
}
// Returns the bit width of the character count field for a segment in the given mode
// in a QR Code at the given version number. The result is in the range [0, 16].
static int numCharCountBits(enum qrcodegen_Mode mode, int version)
{
assert(qrcodegen_VERSION_MIN <= version && version <= qrcodegen_VERSION_MAX);
int i = (version + 7) / 17;
switch(mode) {
case qrcodegen_Mode_NUMERIC : {
static const int temp[] = {10, 12, 14};
return temp[i];
}
case qrcodegen_Mode_ALPHANUMERIC: {
static const int temp[] = { 9, 11, 13};
return temp[i];
}
case qrcodegen_Mode_BYTE : {
static const int temp[] = { 8, 16, 16};
return temp[i];
}
case qrcodegen_Mode_KANJI : {
static const int temp[] = { 8, 10, 12};
return temp[i];
}
case qrcodegen_Mode_ECI :
return 0;
default:
assert(false);
return -1; // Dummy value
}
}
int qrcodegen_getMinFitVersion(enum qrcodegen_Ecc ecl, size_t dataLen)
{
struct qrcodegen_Segment seg;
seg.mode = qrcodegen_Mode_BYTE;
seg.bitLength = calcSegmentBitLength(seg.mode, dataLen);
seg.numChars = (int)dataLen;
for(int version = qrcodegen_VERSION_MIN; version <= qrcodegen_VERSION_MAX; version++) {
int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available
int dataUsedBits = getTotalBits(&seg, 1, version);
if(dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
return version;
}
return -1;
}
int qrcodegen_version2size(int version)
{
if(version < qrcodegen_VERSION_MIN || version > qrcodegen_VERSION_MAX) {
return -1;
}
return ((version - 1) * 4 + 21);
}
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/qrcode/qrcodegen.h | /*
* QR Code generator library (C)
*
* Copyright (c) Project Nayuki. (MIT License)
* https://www.nayuki.io/page/qr-code-generator-library
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* - The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* - The Software is provided "as is", without warranty of any kind, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. In no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the Software or the use or other dealings in the
* Software.
*/
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* This library creates QR Code symbols, which is a type of two-dimension barcode.
* Invented by Denso Wave and described in the ISO/IEC 18004 standard.
* A QR Code structure is an immutable square grid of black and white cells.
* The library provides functions to create a QR Code from text or binary data.
* The library covers the QR Code Model 2 specification, supporting all versions (sizes)
* from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
*
* Ways to create a QR Code object:
* - High level: Take the payload data and call qrcodegen_encodeText() or qrcodegen_encodeBinary().
* - Low level: Custom-make the list of segments and call
* qrcodegen_encodeSegments() or qrcodegen_encodeSegmentsAdvanced().
* (Note that all ways require supplying the desired error correction level and various byte buffers.)
*/
/*---- Enum and struct types----*/
/*
* The error correction level in a QR Code symbol.
*/
enum qrcodegen_Ecc {
// Must be declared in ascending order of error protection
// so that an internal qrcodegen function works properly
qrcodegen_Ecc_LOW = 0, // The QR Code can tolerate about 7% erroneous codewords
qrcodegen_Ecc_MEDIUM, // The QR Code can tolerate about 15% erroneous codewords
qrcodegen_Ecc_QUARTILE, // The QR Code can tolerate about 25% erroneous codewords
qrcodegen_Ecc_HIGH, // The QR Code can tolerate about 30% erroneous codewords
};
/*
* The mask pattern used in a QR Code symbol.
*/
enum qrcodegen_Mask {
// A special value to tell the QR Code encoder to
// automatically select an appropriate mask pattern
qrcodegen_Mask_AUTO = -1,
// The eight actual mask patterns
qrcodegen_Mask_0 = 0,
qrcodegen_Mask_1,
qrcodegen_Mask_2,
qrcodegen_Mask_3,
qrcodegen_Mask_4,
qrcodegen_Mask_5,
qrcodegen_Mask_6,
qrcodegen_Mask_7,
};
/*
* Describes how a segment's data bits are interpreted.
*/
enum qrcodegen_Mode {
qrcodegen_Mode_NUMERIC = 0x1,
qrcodegen_Mode_ALPHANUMERIC = 0x2,
qrcodegen_Mode_BYTE = 0x4,
qrcodegen_Mode_KANJI = 0x8,
qrcodegen_Mode_ECI = 0x7,
};
/*
* A segment of character/binary/control data in a QR Code symbol.
* The mid-level way to create a segment is to take the payload data
* and call a factory function such as qrcodegen_makeNumeric().
* The low-level way to create a segment is to custom-make the bit buffer
* and initialize a qrcodegen_Segment struct with appropriate values.
* Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
* Any segment longer than this is meaningless for the purpose of generating QR Codes.
* Moreover, the maximum allowed bit length is 32767 because
* the largest QR Code (version 40) has 31329 modules.
*/
struct qrcodegen_Segment {
// The mode indicator of this segment.
enum qrcodegen_Mode mode;
// The length of this segment's unencoded data. Measured in characters for
// numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
// Always zero or positive. Not the same as the data's bit length.
int numChars;
// The data bits of this segment, packed in bitwise big endian.
// Can be null if the bit length is zero.
uint8_t * data;
// The number of valid data bits used in the buffer. Requires
// 0 <= bitLength <= 32767, and bitLength <= (capacity of data array) * 8.
// The character count (numChars) must agree with the mode and the bit buffer length.
int bitLength;
};
/*---- Macro constants and functions ----*/
#define qrcodegen_VERSION_MIN 1 // The minimum version number supported in the QR Code Model 2 standard
#define qrcodegen_VERSION_MAX 40 // The maximum version number supported in the QR Code Model 2 standard
// Calculates the number of bytes needed to store any QR Code up to and including the given version number,
// as a compile-time constant. For example, 'uint8_t buffer[qrcodegen_BUFFER_LEN_FOR_VERSION(25)];'
// can store any single QR Code from version 1 to 25 (inclusive). The result fits in an int (or int16).
// Requires qrcodegen_VERSION_MIN <= n <= qrcodegen_VERSION_MAX.
#define qrcodegen_BUFFER_LEN_FOR_VERSION(n) ((((n) * 4 + 17) * ((n) * 4 + 17) + 7) / 8 + 1)
// The worst-case number of bytes needed to store one QR Code, up to and including
// version 40. This value equals 3918, which is just under 4 kilobytes.
// Use this more convenient value to avoid calculating tighter memory bounds for buffers.
#define qrcodegen_BUFFER_LEN_MAX qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX)
/*---- Functions (high level) to generate QR Codes ----*/
/*
* Encodes the given text string to a QR Code, returning true if encoding succeeded.
* If the data is too long to fit in any version in the given range
* at the given ECC level, then false is returned.
* - The input text must be encoded in UTF-8 and contain no NULs.
* - The variables ecl and mask must correspond to enum constant values.
* - Requires 1 <= minVersion <= maxVersion <= 40.
* - The arrays tempBuffer and qrcode must each have a length
* of at least qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion).
* - After the function returns, tempBuffer contains no useful data.
* - If successful, the resulting QR Code may use numeric,
* alphanumeric, or byte mode to encode the text.
* - In the most optimistic case, a QR Code at version 40 with low ECC
* can hold any UTF-8 string up to 2953 bytes, or any alphanumeric string
* up to 4296 characters, or any digit string up to 7089 characters.
* These numbers represent the hard upper limit of the QR Code standard.
* - Please consult the QR Code specification for information on
* data capacities per version, ECC level, and text encoding mode.
*/
bool qrcodegen_encodeText(const char * text, uint8_t tempBuffer[], uint8_t qrcode[],
enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl);
/*
* Encodes the given binary data to a QR Code, returning true if encoding succeeded.
* If the data is too long to fit in any version in the given range
* at the given ECC level, then false is returned.
* - The input array range dataAndTemp[0 : dataLen] should normally be
* valid UTF-8 text, but is not required by the QR Code standard.
* - The variables ecl and mask must correspond to enum constant values.
* - Requires 1 <= minVersion <= maxVersion <= 40.
* - The arrays dataAndTemp and qrcode must each have a length
* of at least qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion).
* - After the function returns, the contents of dataAndTemp may have changed,
* and does not represent useful data anymore.
* - If successful, the resulting QR Code will use byte mode to encode the data.
* - In the most optimistic case, a QR Code at version 40 with low ECC can hold any byte
* sequence up to length 2953. This is the hard upper limit of the QR Code standard.
* - Please consult the QR Code specification for information on
* data capacities per version, ECC level, and text encoding mode.
*/
bool qrcodegen_encodeBinary(uint8_t dataAndTemp[], size_t dataLen, uint8_t qrcode[],
enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl);
/*---- Functions (low level) to generate QR Codes ----*/
/*
* Renders a QR Code representing the given segments at the given error correction level.
* The smallest possible QR Code version is automatically chosen for the output. Returns true if
* QR Code creation succeeded, or false if the data is too long to fit in any version. The ECC level
* of the result may be higher than the ecl argument if it can be done without increasing the version.
* This function allows the user to create a custom sequence of segments that switches
* between modes (such as alphanumeric and byte) to encode text in less space.
* This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary().
* To save memory, the segments' data buffers can alias/overlap tempBuffer, and will
* result in them being clobbered, but the QR Code output will still be correct.
* But the qrcode array must not overlap tempBuffer or any segment's data buffer.
*/
bool qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[], size_t len,
enum qrcodegen_Ecc ecl, uint8_t tempBuffer[], uint8_t qrcode[]);
/*
* Renders a QR Code representing the given segments with the given encoding parameters.
* Returns true if QR Code creation succeeded, or false if the data is too long to fit in the range of versions.
* The smallest possible QR Code version within the given range is automatically
* chosen for the output. Iff boostEcl is true, then the ECC level of the result
* may be higher than the ecl argument if it can be done without increasing the
* version. The mask number is either between 0 to 7 (inclusive) to force that
* mask, or -1 to automatically choose an appropriate mask (which may be slow).
* This function allows the user to create a custom sequence of segments that switches
* between modes (such as alphanumeric and byte) to encode text in less space.
* This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary().
* To save memory, the segments' data buffers can alias/overlap tempBuffer, and will
* result in them being clobbered, but the QR Code output will still be correct.
* But the qrcode array must not overlap tempBuffer or any segment's data buffer.
*/
bool qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[], size_t len, enum qrcodegen_Ecc ecl,
int minVersion, int maxVersion, int mask, bool boostEcl, uint8_t tempBuffer[], uint8_t qrcode[]);
/*
* Tests whether the given string can be encoded as a segment in alphanumeric mode.
* A string is encodable iff each character is in the following set: 0 to 9, A to Z
* (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
*/
bool qrcodegen_isAlphanumeric(const char * text);
/*
* Tests whether the given string can be encoded as a segment in numeric mode.
* A string is encodable iff each character is in the range 0 to 9.
*/
bool qrcodegen_isNumeric(const char * text);
/*
* Returns the number of bytes (uint8_t) needed for the data buffer of a segment
* containing the given number of characters using the given mode. Notes:
* - Returns SIZE_MAX on failure, i.e. numChars > INT16_MAX or
* the number of needed bits exceeds INT16_MAX (i.e. 32767).
* - Otherwise, all valid results are in the range [0, ceil(INT16_MAX / 8)], i.e. at most 4096.
* - It is okay for the user to allocate more bytes for the buffer than needed.
* - For byte mode, numChars measures the number of bytes, not Unicode code points.
* - For ECI mode, numChars must be 0, and the worst-case number of bytes is returned.
* An actual ECI segment can have shorter data. For non-ECI modes, the result is exact.
*/
size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars);
/*
* Returns a segment representing the given binary data encoded in
* byte mode. All input byte arrays are acceptable. Any text string
* can be converted to UTF-8 bytes and encoded as a byte mode segment.
*/
struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[]);
/*
* Returns a segment representing the given string of decimal digits encoded in numeric mode.
*/
struct qrcodegen_Segment qrcodegen_makeNumeric(const char * digits, uint8_t buf[]);
/*
* Returns a segment representing the given text string encoded in alphanumeric mode.
* The characters allowed are: 0 to 9, A to Z (uppercase only), space,
* dollar, percent, asterisk, plus, hyphen, period, slash, colon.
*/
struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char * text, uint8_t buf[]);
/*
* Returns a segment representing an Extended Channel Interpretation
* (ECI) designator with the given assignment value.
*/
struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[]);
/*---- Functions to extract raw data from QR Codes ----*/
/*
* Returns the side length of the given QR Code, assuming that encoding succeeded.
* The result is in the range [21, 177]. Note that the length of the array buffer
* is related to the side length - every 'uint8_t qrcode[]' must have length at least
* qrcodegen_BUFFER_LEN_FOR_VERSION(version), which equals ceil(size^2 / 8 + 1).
*/
int qrcodegen_getSize(const uint8_t qrcode[]);
/*
* Returns the color of the module (pixel) at the given coordinates, which is false
* for white or true for black. The top left corner has the coordinates (x=0, y=0).
* If the given coordinates are out of bounds, then false (white) is returned.
*/
bool qrcodegen_getModule(const uint8_t qrcode[], int x, int y);
/*
* Returns the qrcode size of the specified version. Returns -1 on failure
*/
int qrcodegen_version2size(int version);
/*
* Returns the min version of the data that can be stored. Returns -1 on failure
*/
int qrcodegen_getMinFitVersion(enum qrcodegen_Ecc ecl, size_t dataLen);
#ifdef __cplusplus
}
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/barcode/lv_barcode.c | /**
* @file lv_barcode.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_barcode.h"
#if LV_USE_BARCODE
#include "code128.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_barcode_class
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_barcode_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_barcode_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static bool lv_barcode_change_buf_size(lv_obj_t * obj, int32_t w, int32_t h);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_barcode_class = {
.constructor_cb = lv_barcode_constructor,
.destructor_cb = lv_barcode_destructor,
.width_def = LV_SIZE_CONTENT,
.instance_size = sizeof(lv_barcode_t),
.base_class = &lv_canvas_class,
.name = "barcode",
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_barcode_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;
}
void lv_barcode_set_dark_color(lv_obj_t * obj, lv_color_t color)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_barcode_t * barcode = (lv_barcode_t *)obj;
barcode->dark_color = color;
}
void lv_barcode_set_light_color(lv_obj_t * obj, lv_color_t color)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_barcode_t * barcode = (lv_barcode_t *)obj;
barcode->light_color = color;
}
void lv_barcode_set_scale(lv_obj_t * obj, uint16_t scale)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
if(scale == 0) {
scale = 1;
}
lv_barcode_t * barcode = (lv_barcode_t *)obj;
barcode->scale = scale;
}
void lv_barcode_set_direction(lv_obj_t * obj, lv_dir_t direction)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_barcode_t * barcode = (lv_barcode_t *)obj;
barcode->direction = direction;
}
lv_result_t lv_barcode_update(lv_obj_t * obj, const char * data)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(data);
lv_result_t res = LV_RESULT_INVALID;
lv_barcode_t * barcode = (lv_barcode_t *)obj;
if(data == NULL || lv_strlen(data) == 0) {
LV_LOG_WARN("data is empty");
return LV_RESULT_INVALID;
}
size_t len = code128_estimate_len(data);
LV_LOG_INFO("data: %s, len = %zu", data, len);
char * out_buf = lv_malloc(len);
LV_ASSERT_MALLOC(out_buf);
if(!out_buf) {
LV_LOG_ERROR("malloc failed for out_buf");
return LV_RESULT_INVALID;
}
int32_t barcode_w = code128_encode_gs1(data, out_buf, len);
LV_LOG_INFO("barcode width = %d", (int)barcode_w);
LV_ASSERT(barcode->scale > 0);
uint16_t scale = barcode->scale;
int32_t buf_w = (barcode->direction == LV_DIR_HOR) ? barcode_w * scale : 1;
int32_t buf_h = (barcode->direction == LV_DIR_VER) ? barcode_w * scale : 1;
if(!lv_barcode_change_buf_size(obj, buf_w, buf_h)) {
goto failed;
}
lv_canvas_set_palette(obj, 0, lv_color_to_32(barcode->dark_color, 0xff));
lv_canvas_set_palette(obj, 1, lv_color_to_32(barcode->light_color, 0xff));
for(int32_t x = 0; x < barcode_w; x++) {
lv_color_t color;
color = lv_color_from_int(out_buf[x] ? 0 : 1);
for(uint16_t i = 0; i < scale; i++) {
if(barcode->direction == LV_DIR_HOR) {
lv_canvas_set_px(obj, x * scale + i, 0, color, LV_OPA_COVER);
}
else {
lv_canvas_set_px(obj, 0, x * scale + i, color, LV_OPA_COVER);
}
}
}
res = LV_RESULT_OK;
failed:
lv_free(out_buf);
return res;
}
lv_color_t lv_barcode_get_dark_color(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_barcode_t * barcode = (lv_barcode_t *)obj;
return barcode->dark_color;
}
lv_color_t lv_barcode_get_light_color(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_barcode_t * barcode = (lv_barcode_t *)obj;
return barcode->light_color;
}
uint16_t lv_barcode_get_scale(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_barcode_t * barcode = (lv_barcode_t *)obj;
return barcode->scale;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_barcode_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_barcode_t * barcode = (lv_barcode_t *)obj;
barcode->dark_color = lv_color_black();
barcode->light_color = lv_color_white();
barcode->scale = 1;
barcode->direction = LV_DIR_HOR;
}
static void lv_barcode_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_image_dsc_t * img = lv_canvas_get_image(obj);
lv_cache_lock();
lv_cache_invalidate(lv_cache_find(img, LV_CACHE_SRC_TYPE_PTR, 0, 0));
lv_cache_unlock();
if(!img->data) {
LV_LOG_INFO("canvas buffer is NULL");
return;
}
LV_LOG_INFO("free canvas buffer: %p", img->data);
lv_free((void *)img->data);
img->data = NULL;
}
static bool lv_barcode_change_buf_size(lv_obj_t * obj, int32_t w, int32_t h)
{
LV_ASSERT_NULL(obj);
LV_ASSERT(w > 0);
lv_image_dsc_t * img = lv_canvas_get_image(obj);
void * buf = (void *)img->data;
uint32_t buf_size = LV_CANVAS_BUF_SIZE_INDEXED_1BIT(w, h);
buf = lv_realloc(buf, buf_size);
LV_ASSERT_MALLOC(buf);
if(!buf) {
LV_LOG_ERROR("malloc failed for canvas buffer");
return false;
}
lv_canvas_set_buffer(obj, buf, w, h, LV_COLOR_FORMAT_I1);
LV_LOG_INFO("set canvas buffer: %p, width = %d", buf, (int)w);
return true;
}
#endif /*LV_USE_BARCODE*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/barcode/code128.c | // Copyright (c) 2013, LKC Technologies, Inc.
// 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. 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../../../lvgl.h"
#if LV_USE_BARCODE
#include "code128.h"
#include <string.h>
#define CODE128_MALLOC lv_malloc
#define CODE128_REALLOC lv_realloc
#define CODE128_FREE lv_free
#define CODE128_MEMSET lv_memset
#define CODE128_STRLEN lv_strlen
#define CODE128_ASSERT LV_ASSERT
#define CODE128_QUIET_ZONE_LEN 10
#define CODE128_CHAR_LEN 11
#define CODE128_STOP_CODE_LEN 13
#define CODE128_START_CODE_A 103
#define CODE128_START_CODE_B 104
#define CODE128_START_CODE_C 105
#define CODE128_MODE_A 'a'
#define CODE128_MODE_B 'b'
#define CODE128_MODE_C 'c'
#define CODE128_MIN_ENCODE_LEN (CODE128_QUIET_ZONE_LEN * 2 + CODE128_CHAR_LEN * 2 + CODE128_STOP_CODE_LEN)
static const int code128_pattern[] = {
// value: pattern, bar/space widths
1740, // 0: 11011001100, 212222
1644, // 1: 11001101100, 222122
1638, // 2: 11001100110, 222221
1176, // 3: 10010011000, 121223
1164, // 4: 10010001100, 121322
1100, // 5: 10001001100, 131222
1224, // 6: 10011001000, 122213
1220, // 7: 10011000100, 122312
1124, // 8: 10001100100, 132212
1608, // 9: 11001001000, 221213
1604, // 10: 11001000100, 221312
1572, // 11: 11000100100, 231212
1436, // 12: 10110011100, 112232
1244, // 13: 10011011100, 122132
1230, // 14: 10011001110, 122231
1484, // 15: 10111001100, 113222
1260, // 16: 10011101100, 123122
1254, // 17: 10011100110, 123221
1650, // 18: 11001110010, 223211
1628, // 19: 11001011100, 221132
1614, // 20: 11001001110, 221231
1764, // 21: 11011100100, 213212
1652, // 22: 11001110100, 223112
1902, // 23: 11101101110, 312131
1868, // 24: 11101001100, 311222
1836, // 25: 11100101100, 321122
1830, // 26: 11100100110, 321221
1892, // 27: 11101100100, 312212
1844, // 28: 11100110100, 322112
1842, // 29: 11100110010, 322211
1752, // 30: 11011011000, 212123
1734, // 31: 11011000110, 212321
1590, // 32: 11000110110, 232121
1304, // 33: 10100011000, 111323
1112, // 34: 10001011000, 131123
1094, // 35: 10001000110, 131321
1416, // 36: 10110001000, 112313
1128, // 37: 10001101000, 132113
1122, // 38: 10001100010, 132311
1672, // 39: 11010001000, 211313
1576, // 40: 11000101000, 231113
1570, // 41: 11000100010, 231311
1464, // 42: 10110111000, 112133
1422, // 43: 10110001110
1134, // 44: 10001101110
1496, // 45: 10111011000, 113123
1478, // 46: 10111000110, 113321
1142, // 47: 10001110110, 133121
1910, // 48: 11101110110, 313121
1678, // 49: 11010001110, 211331
1582, // 50: 11000101110, 231131
1768, // 51: 11011101000, 213113
1762, // 52: 11011100010, 213311
1774, // 53: 11011101110, 213131
1880, // 54: 11101011000, 311123
1862, // 55: 11101000110, 311321
1814, // 56: 11100010110, 331121
1896, // 57: 11101101000, 312113
1890, // 58: 11101100010, 312311
1818, // 59: 11100011010, 332111
1914, // 60: 11101111010, 314111
1602, // 61: 11001000010, 221411
1930, // 62: 11110001010, 431111
1328, // 63: 10100110000, 111224
1292, // 64: 10100001100, 111422
1200, // 65: 10010110000, 121124
1158, // 66: 10010000110, 121421
1068, // 67: 10000101100, 141122
1062, // 68: 10000100110, 141221
1424, // 69: 10110010000, 112214
1412, // 70: 10110000100, 112412
1232, // 71: 10011010000, 122114
1218, // 72: 10011000010, 122411
1076, // 73: 10000110100, 142112
1074, // 74: 10000110010, 142211
1554, // 75: 11000010010, 241211
1616, // 76: 11001010000, 221114
1978, // 77: 11110111010, 413111
1556, // 78: 11000010100, 241112
1146, // 79: 10001111010, 134111
1340, // 80: 10100111100, 111242
1212, // 81: 10010111100, 121142
1182, // 82: 10010011110, 121241
1508, // 83: 10111100100, 114212
1268, // 84: 10011110100, 124112
1266, // 85: 10011110010, 124211
1956, // 86: 11110100100, 411212
1940, // 87: 11110010100, 421112
1938, // 88: 11110010010, 421211
1758, // 89: 11011011110, 212141
1782, // 90: 11011110110, 214121
1974, // 91: 11110110110, 412121
1400, // 92: 10101111000, 111143
1310, // 93: 10100011110, 111341
1118, // 94: 10001011110, 131141
1512, // 95: 10111101000, 114113
1506, // 96: 10111100010, 114311
1960, // 97: 11110101000, 411113
1954, // 98: 11110100010, 411311
1502, // 99: 10111011110, 113141
1518, // 100: 10111101110, 114131
1886, // 101: 11101011110, 311141
1966, // 102: 11110101110, 411131
1668, // 103: 11010000100, 211412
1680, // 104: 11010010000, 211214
1692 // 105: 11010011100, 211232
};
static const int code128_stop_pattern = 6379; // 1100011101011, 2331112
struct code128_step {
int prev_ix; // Index of previous step, if any
const char * next_input; // Remaining input
unsigned short len; // The length of the pattern so far (includes this step)
char mode; // State for the current encoding
signed char code; // What code should be written for this step
};
struct code128_state {
struct code128_step * steps;
int allocated_steps;
int current_ix;
int todo_ix;
int best_ix;
size_t maxlength;
};
size_t code128_estimate_len(const char * s)
{
return CODE128_QUIET_ZONE_LEN
+ CODE128_CHAR_LEN // start code
+ CODE128_CHAR_LEN * (CODE128_STRLEN(s) * 11 / 10) // contents + 10% padding
+ CODE128_CHAR_LEN // checksum
+ CODE128_STOP_CODE_LEN
+ CODE128_QUIET_ZONE_LEN;
}
static void code128_append_pattern(int pattern, int pattern_length, char * out)
{
// All patterns have their first bit set by design
CODE128_ASSERT(pattern & (1 << (pattern_length - 1)));
int i;
for(i = pattern_length - 1; i >= 0; i--) {
// cast avoids warning: implicit conversion from 'int' to 'char' changes value from 255 to -1 [-Wconstant-conversion]
*out++ = (unsigned char)((pattern & (1 << i)) ? 255 : 0);
}
}
static int code128_append_code(int code, char * out)
{
CODE128_ASSERT(code >= 0 && code < (int)(sizeof(code128_pattern) / sizeof(code128_pattern[0])));
code128_append_pattern(code128_pattern[code], CODE128_CHAR_LEN, out);
return CODE128_CHAR_LEN;
}
static int code128_append_stop_code(char * out)
{
code128_append_pattern(code128_stop_pattern, CODE128_STOP_CODE_LEN, out);
return CODE128_STOP_CODE_LEN;
}
static signed char code128_switch_code(char from_mode, char to_mode)
{
switch(from_mode) {
case CODE128_MODE_A:
switch(to_mode) {
case CODE128_MODE_B:
return 100;
case CODE128_MODE_C:
return 99;
}
break;
case CODE128_MODE_B:
switch(to_mode) {
case CODE128_MODE_A:
return 101;
case CODE128_MODE_C:
return 99;
}
break;
case CODE128_MODE_C:
switch(to_mode) {
case CODE128_MODE_B:
return 100;
case CODE128_MODE_A:
return 101;
}
break;
default:
break;
}
CODE128_ASSERT(0); // Invalid mode switch
return -1;
}
static signed char code128a_ascii_to_code(signed char value)
{
if(value >= ' ' && value <= '_')
return (signed char)(value - ' ');
else if(value >= 0 && value < ' ')
return (signed char)(value + 64);
else if(value == (signed char)CODE128_FNC1)
return 102;
else if(value == (signed char)CODE128_FNC2)
return 97;
else if(value == (signed char)CODE128_FNC3)
return 96;
else if(value == (signed char)CODE128_FNC4)
return 101;
else
return -1;
}
static signed char code128b_ascii_to_code(signed char value)
{
if(value >= ' ') // value <= 127 is implied
return (signed char)(value - ' ');
else if(value == (signed char)CODE128_FNC1)
return 102;
else if(value == (signed char)CODE128_FNC2)
return 97;
else if(value == (signed char)CODE128_FNC3)
return 96;
else if(value == (signed char)CODE128_FNC4)
return 100;
else
return -1;
}
static signed char code128c_ascii_to_code(const char * values)
{
if(values[0] == CODE128_FNC1)
return 102;
if(values[0] >= '0' && values[0] <= '9' &&
values[1] >= '0' && values[1] <= '9') {
char code = 10 * (values[0] - '0') + (values[1] - '0');
return code;
}
return -1;
}
static int code128_do_a_step(struct code128_step * base, int prev_ix, int ix)
{
struct code128_step * previous_step = &base[prev_ix];
struct code128_step * step = &base[ix];
char value = *previous_step->next_input;
// NOTE: Currently we can't encode NULL
if(value == 0)
return 0;
step->code = code128a_ascii_to_code(value);
if(step->code < 0)
return 0;
step->prev_ix = prev_ix;
step->next_input = previous_step->next_input + 1;
step->mode = CODE128_MODE_A;
step->len = previous_step->len + CODE128_CHAR_LEN;
if(step->mode != previous_step->mode)
step->len += CODE128_CHAR_LEN; // Need to switch modes
return 1;
}
static int code128_do_b_step(struct code128_step * base, int prev_ix, int ix)
{
struct code128_step * previous_step = &base[prev_ix];
struct code128_step * step = &base[ix];
char value = *previous_step->next_input;
// NOTE: Currently we can't encode NULL
if(value == 0)
return 0;
step->code = code128b_ascii_to_code(value);
if(step->code < 0)
return 0;
step->prev_ix = prev_ix;
step->next_input = previous_step->next_input + 1;
step->mode = CODE128_MODE_B;
step->len = previous_step->len + CODE128_CHAR_LEN;
if(step->mode != previous_step->mode)
step->len += CODE128_CHAR_LEN; // Need to switch modes
return 1;
}
static int code128_do_c_step(struct code128_step * base, int prev_ix, int ix)
{
struct code128_step * previous_step = &base[prev_ix];
struct code128_step * step = &base[ix];
char value = *previous_step->next_input;
// NOTE: Currently we can't encode NULL
if(value == 0)
return 0;
step->code = code128c_ascii_to_code(previous_step->next_input);
if(step->code < 0)
return 0;
step->prev_ix = prev_ix;
step->next_input = previous_step->next_input + 1;
// Mode C consumes 2 characters for codes 0-99
if(step->code < 100)
step->next_input++;
step->mode = CODE128_MODE_C;
step->len = previous_step->len + CODE128_CHAR_LEN;
if(step->mode != previous_step->mode)
step->len += CODE128_CHAR_LEN; // Need to switch modes
return 1;
}
static struct code128_step * code128_alloc_step(struct code128_state * state)
{
if(state->todo_ix >= state->allocated_steps) {
state->allocated_steps += 1024;
state->steps = (struct code128_step *) CODE128_REALLOC(state->steps,
state->allocated_steps * sizeof(struct code128_step));
}
struct code128_step * step = &state->steps[state->todo_ix];
CODE128_MEMSET(step, 0, sizeof(*step));
return step;
}
static void code128_do_step(struct code128_state * state)
{
struct code128_step * step = &state->steps[state->current_ix];
if(*step->next_input == 0) {
// Done, so see if we have a new shortest encoding.
if((step->len < state->maxlength) ||
(state->best_ix < 0 && step->len == state->maxlength)) {
state->best_ix = state->current_ix;
// Update maxlength to avoid considering anything longer
state->maxlength = step->len;
}
return;
}
// Don't try if we're already at or beyond the max acceptable
// length;
if(step->len >= state->maxlength)
return;
char mode = step->mode;
code128_alloc_step(state);
int mode_c_worked = 0;
// Always try mode C
if(code128_do_c_step(state->steps, state->current_ix, state->todo_ix)) {
state->todo_ix++;
code128_alloc_step(state);
mode_c_worked = 1;
}
if(mode == CODE128_MODE_A) {
// If A works, stick with A. There's no advantage to switching
// to B proactively if A still works.
if(code128_do_a_step(state->steps, state->current_ix, state->todo_ix) ||
code128_do_b_step(state->steps, state->current_ix, state->todo_ix))
state->todo_ix++;
}
else if(mode == CODE128_MODE_B) {
// The same logic applies here. There's no advantage to switching
// proactively to A if B still works.
if(code128_do_b_step(state->steps, state->current_ix, state->todo_ix) ||
code128_do_a_step(state->steps, state->current_ix, state->todo_ix))
state->todo_ix++;
}
else if(!mode_c_worked) {
// In mode C. If mode C worked and we're in mode C, trying anything
// else is pointless since the mode C encoding will be shorter and
// there won't be any mode switches.
// If we're leaving mode C, though, try both in case one ends up
// better than the other.
if(code128_do_a_step(state->steps, state->current_ix, state->todo_ix)) {
state->todo_ix++;
code128_alloc_step(state);
}
if(code128_do_b_step(state->steps, state->current_ix, state->todo_ix))
state->todo_ix++;
}
}
size_t code128_encode_raw(const char * s, char * out, size_t maxlength)
{
struct code128_state state;
const size_t overhead = CODE128_QUIET_ZONE_LEN
+ CODE128_CHAR_LEN // checksum
+ CODE128_STOP_CODE_LEN
+ CODE128_QUIET_ZONE_LEN;
if(maxlength < overhead + CODE128_CHAR_LEN + CODE128_CHAR_LEN) {
// Need space to encode the start character and one additional
// character.
return 0;
}
state.allocated_steps = 256;
state.steps = (struct code128_step *) CODE128_MALLOC(state.allocated_steps * sizeof(struct code128_step));
state.current_ix = 0;
state.todo_ix = 0;
state.maxlength = maxlength - overhead;
state.best_ix = -1;
// Initialize the first 3 steps for the 3 encoding routes (A, B, C)
state.steps[0].prev_ix = -1;
state.steps[0].next_input = s;
state.steps[0].len = CODE128_CHAR_LEN;
state.steps[0].mode = CODE128_MODE_C;
state.steps[0].code = CODE128_START_CODE_C;
state.steps[1].prev_ix = -1;
state.steps[1].next_input = s;
state.steps[1].len = CODE128_CHAR_LEN;
state.steps[1].mode = CODE128_MODE_A;
state.steps[1].code = CODE128_START_CODE_A;
state.steps[2].prev_ix = -1;
state.steps[2].next_input = s;
state.steps[2].len = CODE128_CHAR_LEN;
state.steps[2].mode = CODE128_MODE_B;
state.steps[2].code = CODE128_START_CODE_B;
state.todo_ix = 3;
// Keep going until no more work
do {
code128_do_step(&state);
state.current_ix++;
} while(state.current_ix != state.todo_ix);
// If no best_step, then fail.
if(state.best_ix < 0) {
CODE128_FREE(state.steps);
return 0;
}
// Determine the list of codes
size_t num_codes = state.maxlength / CODE128_CHAR_LEN;
char * codes = CODE128_MALLOC(num_codes);
CODE128_ASSERT(codes);
struct code128_step * step = &state.steps[state.best_ix];
size_t i;
for(i = num_codes - 1; i > 0; --i) {
struct code128_step * prev_step = &state.steps[step->prev_ix];
codes[i] = step->code;
if(step->mode != prev_step->mode) {
--i;
codes[i] = code128_switch_code(prev_step->mode, step->mode);
}
step = prev_step;
}
codes[0] = step->code;
// Encode everything up to the checksum
size_t actual_length = state.maxlength + overhead;
CODE128_MEMSET(out, 0, CODE128_QUIET_ZONE_LEN);
out += CODE128_QUIET_ZONE_LEN;
for(i = 0; i < num_codes; i++)
out += code128_append_code(codes[i], out);
// Compute the checksum
int sum = codes[0];
for(i = 1; i < num_codes; i++)
sum += codes[i] * i;
out += code128_append_code(sum % 103, out);
// Finalize the code.
out += code128_append_stop_code(out);
CODE128_MEMSET(out, 0, CODE128_QUIET_ZONE_LEN);
CODE128_FREE(codes);
CODE128_FREE(state.steps);
return actual_length;
}
/**
* @brief Encode the GS1 string
*
* This converts [FNC1] sequences to raw FNC1 characters and
* removes spaces before encoding the barcodes.
*
* @return the length of barcode data in bytes
*/
size_t code128_encode_gs1(const char * s, char * out, size_t maxlength)
{
size_t raw_size = CODE128_STRLEN(s) + 1;
char * raw = CODE128_MALLOC(raw_size);
CODE128_ASSERT(raw);
if(!raw) {
return 0;
}
char * p = raw;
for(; *s != '\0'; s++) {
if(strncmp(s, "[FNC1]", 6) == 0) {
*p++ = CODE128_FNC1;
s += 5;
}
else if(*s != ' ') {
*p++ = *s;
}
}
*p = '\0';
size_t length = code128_encode_raw(raw, out, maxlength);
CODE128_FREE(raw);
return length;
}
#endif /*LV_USE_BARCODE*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/barcode/lv_barcode.h | /**
* @file lv_barcode.c
*
*/
#ifndef LV_BARCODE_H
#define LV_BARCODE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_BARCODE
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/*Data of barcode*/
typedef struct {
lv_canvas_t canvas;
lv_color_t dark_color;
lv_color_t light_color;
uint16_t scale;
lv_dir_t direction;
} lv_barcode_t;
extern const lv_obj_class_t lv_barcode_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create an empty barcode (an `lv_canvas`) object.
* @param parent point to an object where to create the barcode
* @return pointer to the created barcode object
*/
lv_obj_t * lv_barcode_create(lv_obj_t * parent);
/**
* Set the dark color of a barcode object
* @param obj pointer to barcode object
* @param color dark color of the barcode
*/
void lv_barcode_set_dark_color(lv_obj_t * obj, lv_color_t color);
/**
* Set the light color of a barcode object
* @param obj pointer to barcode object
* @param color light color of the barcode
*/
void lv_barcode_set_light_color(lv_obj_t * obj, lv_color_t color);
/**
* Set the scale of a barcode object
* @param obj pointer to barcode object
* @param scale scale factor
*/
void lv_barcode_set_scale(lv_obj_t * obj, uint16_t scale);
/**
* Set the direction of a barcode object
* @param obj pointer to barcode object
* @param direction draw direction (`LV_DIR_HOR` or `LB_DIR_VER`)
*/
void lv_barcode_set_direction(lv_obj_t * obj, lv_dir_t direction);
/**
* Set the data of a barcode object
* @param obj pointer to barcode object
* @param data data to display
* @return LV_RESULT_OK: if no error; LV_RESULT_INVALID: on error
*/
lv_result_t lv_barcode_update(lv_obj_t * obj, const char * data);
/**
* Get the dark color of a barcode object
* @param obj pointer to barcode object
* @return dark color of the barcode
*/
lv_color_t lv_barcode_get_dark_color(lv_obj_t * obj);
/**
* Get the light color of a barcode object
* @param obj pointer to barcode object
* @return light color of the barcode
*/
lv_color_t lv_barcode_get_light_color(lv_obj_t * obj);
/**
* Get the scale of a barcode object
* @param obj pointer to barcode object
* @return scale factor
*/
uint16_t lv_barcode_get_scale(lv_obj_t * obj);
/**********************
* MACROS
**********************/
#endif /*LV_USE_BARCODE*/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*LV_BARCODE_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/barcode/code128.h | // Copyright (c) 2013-15, LKC Technologies, Inc.
// 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. 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef CODE128_H
#define CODE128_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
// Since the FNCn characters are not ASCII, define versions here to
// simplify encoding strings that include them.
#define CODE128_FNC1 '\xf1'
#define CODE128_FNC2 '\xf2'
#define CODE128_FNC3 '\xf3'
#define CODE128_FNC4 '\xf4'
size_t code128_estimate_len(const char * s);
size_t code128_encode_gs1(const char * s, char * out, size_t maxlength);
size_t code128_encode_raw(const char * s, char * out, size_t maxlength);
#ifdef __cplusplus
}
#endif
#endif // CODE128_H
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/fsdrv/lv_fs_posix.c | /**
* @file lv_fs_posix.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_FS_POSIX
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#ifndef WIN32
#include <dirent.h>
#include <unistd.h>
#else
#include <windows.h>
#endif
#include "../../core/lv_global.h"
/*********************
* DEFINES
*********************/
#if LV_FS_POSIX_LETTER == '\0'
#error "LV_FS_POSIX_LETTER must be an upper case ASCII letter"
#endif
/** The reason for 'fd + 1' is because open() may return a legal fd with a value of 0,
* preventing it from being judged as NULL when converted to a pointer type.
*/
#define FILEP2FD(file_p) ((lv_uintptr_t)file_p - 1)
#define FD2FILEP(fd) ((void *)(lv_uintptr_t)(fd + 1))
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void * fs_open(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode);
static lv_fs_res_t fs_close(lv_fs_drv_t * drv, void * file_p);
static lv_fs_res_t fs_read(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br);
static lv_fs_res_t fs_write(lv_fs_drv_t * drv, void * file_p, const void * buf, uint32_t btw, uint32_t * bw);
static lv_fs_res_t fs_seek(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t whence);
static lv_fs_res_t fs_tell(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p);
static void * fs_dir_open(lv_fs_drv_t * drv, const char * path);
static lv_fs_res_t fs_dir_read(lv_fs_drv_t * drv, void * dir_p, char * fn);
static lv_fs_res_t fs_dir_close(lv_fs_drv_t * drv, void * dir_p);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Register a driver for the File system interface
*/
void lv_fs_posix_init(void)
{
/*---------------------------------------------------
* Register the file system interface in LVGL
*--------------------------------------------------*/
/*Add a simple drive to open images*/
lv_fs_drv_t * fs_drv_p = &(LV_GLOBAL_DEFAULT()->posix_fs_drv);
lv_fs_drv_init(fs_drv_p);
/*Set up fields...*/
fs_drv_p->letter = LV_FS_POSIX_LETTER;
fs_drv_p->cache_size = LV_FS_POSIX_CACHE_SIZE;
fs_drv_p->open_cb = fs_open;
fs_drv_p->close_cb = fs_close;
fs_drv_p->read_cb = fs_read;
fs_drv_p->write_cb = fs_write;
fs_drv_p->seek_cb = fs_seek;
fs_drv_p->tell_cb = fs_tell;
fs_drv_p->dir_close_cb = fs_dir_close;
fs_drv_p->dir_open_cb = fs_dir_open;
fs_drv_p->dir_read_cb = fs_dir_read;
lv_fs_drv_register(fs_drv_p);
}
/**********************
* STATIC FUNCTIONS
**********************/
/**
* Open a file
* @param drv pointer to a driver where this function belongs
* @param path path to the file beginning with the driver letter (e.g. S:/folder/file.txt)
* @param mode read: FS_MODE_RD, write: FS_MODE_WR, both: FS_MODE_RD | FS_MODE_WR
* @return a file handle or -1 in case of fail
*/
static void * fs_open(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode)
{
LV_UNUSED(drv);
uint32_t flags = 0;
if(mode == LV_FS_MODE_WR) flags = O_WRONLY | O_CREAT;
else if(mode == LV_FS_MODE_RD) flags = O_RDONLY;
else if(mode == (LV_FS_MODE_WR | LV_FS_MODE_RD)) flags = O_RDWR | O_CREAT;
/*Make the path relative to the current directory (the projects root folder)*/
char buf[256];
lv_snprintf(buf, sizeof(buf), LV_FS_POSIX_PATH "%s", path);
int f = open(buf, flags, 0666);
if(f < 0) return NULL;
return FD2FILEP(f);
}
/**
* Close an opened file
* @param drv pointer to a driver where this function belongs
* @param file_p a file handle. (opened with fs_open)
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_close(lv_fs_drv_t * drv, void * file_p)
{
LV_UNUSED(drv);
close(FILEP2FD(file_p));
return LV_FS_RES_OK;
}
/**
* Read data from an opened file
* @param drv pointer to a driver where this function belongs
* @param file_p a file handle variable.
* @param buf pointer to a memory block where to store the read data
* @param btr number of Bytes To Read
* @param br the real number of read bytes (Byte Read)
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_read(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br)
{
LV_UNUSED(drv);
*br = read(FILEP2FD(file_p), buf, btr);
return (int32_t)(*br) < 0 ? LV_FS_RES_UNKNOWN : LV_FS_RES_OK;
}
/**
* Write into a file
* @param drv pointer to a driver where this function belongs
* @param file_p a file handle variable
* @param buf pointer to a buffer with the bytes to write
* @param btw Bytes To Write
* @param bw the number of real written bytes (Bytes Written). NULL if unused.
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_write(lv_fs_drv_t * drv, void * file_p, const void * buf, uint32_t btw, uint32_t * bw)
{
LV_UNUSED(drv);
*bw = write(FILEP2FD(file_p), buf, btw);
return (int32_t)(*bw) < 0 ? LV_FS_RES_UNKNOWN : LV_FS_RES_OK;
}
/**
* Set the read write pointer. Also expand the file size if necessary.
* @param drv pointer to a driver where this function belongs
* @param file_p a file handle variable. (opened with fs_open )
* @param pos the new position of read write pointer
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_seek(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t whence)
{
LV_UNUSED(drv);
int w;
switch(whence) {
case LV_FS_SEEK_SET:
w = SEEK_SET;
break;
case LV_FS_SEEK_CUR:
w = SEEK_CUR;
break;
case LV_FS_SEEK_END:
w = SEEK_END;
break;
default:
return LV_FS_RES_INV_PARAM;
}
off_t offset = lseek(FILEP2FD(file_p), pos, w);
return offset < 0 ? LV_FS_RES_FS_ERR : LV_FS_RES_OK;
}
/**
* Give the position of the read write pointer
* @param drv pointer to a driver where this function belongs
* @param file_p a file handle variable.
* @param pos_p pointer to to store the result
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_tell(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p)
{
LV_UNUSED(drv);
off_t offset = lseek(FILEP2FD(file_p), 0, SEEK_CUR);
*pos_p = offset;
return offset < 0 ? LV_FS_RES_FS_ERR : LV_FS_RES_OK;
}
#ifdef WIN32
static char next_fn[256];
#endif
/**
* Initialize a 'fs_read_dir_t' variable for directory reading
* @param drv pointer to a driver where this function belongs
* @param path path to a directory
* @return pointer to an initialized 'DIR' or 'HANDLE' variable
*/
static void * fs_dir_open(lv_fs_drv_t * drv, const char * path)
{
LV_UNUSED(drv);
#ifndef WIN32
/*Make the path relative to the current directory (the projects root folder)*/
char buf[256];
lv_snprintf(buf, sizeof(buf), LV_FS_POSIX_PATH "%s", path);
return opendir(buf);
#else
HANDLE d = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA fdata;
/*Make the path relative to the current directory (the projects root folder)*/
char buf[256];
lv_snprintf(buf, sizeof(buf), LV_FS_POSIX_PATH "%s\\*", path);
lv_strcpy(next_fn, "");
d = FindFirstFile(buf, &fdata);
do {
if(strcmp(fdata.cFileName, ".") == 0 || strcmp(fdata.cFileName, "..") == 0) {
continue;
}
else {
if(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
sprintf(next_fn, "/%s", fdata.cFileName);
}
else {
sprintf(next_fn, "%s", fdata.cFileName);
}
break;
}
} while(FindNextFileA(d, &fdata));
return d;
#endif
}
/**
* Read the next filename from a directory.
* The name of the directories will begin with '/'
* @param drv pointer to a driver where this function belongs
* @param dir_p pointer to an initialized 'DIR' or 'HANDLE' variable
* @param fn pointer to a buffer to store the filename
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_dir_read(lv_fs_drv_t * drv, void * dir_p, char * fn)
{
LV_UNUSED(drv);
#ifndef WIN32
struct dirent * entry;
do {
entry = readdir(dir_p);
if(entry) {
if(entry->d_type == DT_DIR) sprintf(fn, "/%s", entry->d_name);
else lv_strcpy(fn, entry->d_name);
}
else {
lv_strcpy(fn, "");
}
} while(strcmp(fn, "/.") == 0 || strcmp(fn, "/..") == 0);
#else
lv_strcpy(fn, next_fn);
lv_strcpy(next_fn, "");
WIN32_FIND_DATA fdata;
if(FindNextFile(dir_p, &fdata) == false) return LV_FS_RES_OK;
do {
if(strcmp(fdata.cFileName, ".") == 0 || strcmp(fdata.cFileName, "..") == 0) {
continue;
}
else {
if(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
sprintf(next_fn, "/%s", fdata.cFileName);
}
else {
sprintf(next_fn, "%s", fdata.cFileName);
}
break;
}
} while(FindNextFile(dir_p, &fdata));
#endif
return LV_FS_RES_OK;
}
/**
* Close the directory reading
* @param drv pointer to a driver where this function belongs
* @param dir_p pointer to an initialized 'DIR' or 'HANDLE' variable
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_dir_close(lv_fs_drv_t * drv, void * dir_p)
{
LV_UNUSED(drv);
#ifndef WIN32
closedir(dir_p);
#else
FindClose(dir_p);
#endif
return LV_FS_RES_OK;
}
#else /*LV_USE_FS_POSIX == 0*/
#if defined(LV_FS_POSIX_LETTER) && LV_FS_POSIX_LETTER != '\0'
#warning "LV_USE_FS_POSIX is not enabled but LV_FS_POSIX_LETTER is set"
#endif
#endif /*LV_USE_FS_POSIX*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/fsdrv/lv_fs_cbfs.c | // this file should not exist
#ifdef __GNUC__
#define IS_NOT_USED __attribute__ ((unused))
#else
#define IS_NOT_USED
#endif
IS_NOT_USED static void nothing(void)
{
// do nothing
} |
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/fsdrv/lv_fs_memfs.c | /**
* @file lv_fs_memfs.c
*
* File System Interface driver for memory-mapped files
*
* This driver allows using a memory area as a file that can be read by normal file operations. It can
* be used, e.g., to store font files in slow flash memory, and load them into RAM on demand.
*
* You can enable it in lv_conf.h:
*
* #define LV_USE_FS_MEMFS 1
*
* The actual implementation uses the built-in cache mechanism of the file system interface.
*
* Since this is not an actual file system, file write and directories are not supported.
*
* The default drive letter is 'M', but this can be changed in lv_conf.h:
*
* #define LV_FS_MEMFS_LETTER 'M'
*
* To use it seamlessly with the file system interface a new extended path object has been introduced:
*
* lv_fs_path_ex_t mempath;
*
* This structure can be initialized with the helper function:
*
* lv_fs_make_path_ex(&mempath, (const uint8_t *) & my_mem_buffer, sizeof(my_mem_buffer));
*
* Then the "file" can be opened with:
*
* lv_fs_file_t file;
* lv_fs_res_t res = lv_fs_open(&file, (const char *) & mempath, LV_FS_MODE_RD);
*
* The path object can be used at any place where a file path is required, e.g.:
*
* lv_font_t* my_font = lv_font_load((const char *) & mempath);
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_FS_MEMFS
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void * fs_open(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode);
static lv_fs_res_t fs_close(lv_fs_drv_t * drv, void * file_p);
static lv_fs_res_t fs_read(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br);
static lv_fs_res_t fs_seek(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t whence);
static lv_fs_res_t fs_tell(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p);
/**********************
* STATIC VARIABLES
**********************/
static lv_fs_drv_t fs_drv; /*A driver descriptor*/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Register a driver for the File system interface
*/
void lv_fs_memfs_init(void)
{
/*---------------------------------------------------
* Register the file system interface in LVGL
*--------------------------------------------------*/
/*Add a simple drive to open images*/
lv_fs_drv_init(&fs_drv);
/*Set up fields...*/
fs_drv.letter = LV_FS_MEMFS_LETTER;
fs_drv.cache_size = LV_FS_CACHE_FROM_BUFFER;
fs_drv.open_cb = fs_open;
fs_drv.close_cb = fs_close;
fs_drv.read_cb = fs_read;
fs_drv.write_cb = NULL;
fs_drv.seek_cb = fs_seek;
fs_drv.tell_cb = fs_tell;
fs_drv.dir_close_cb = NULL;
fs_drv.dir_open_cb = NULL;
fs_drv.dir_read_cb = NULL;
lv_fs_drv_register(&fs_drv);
}
/**********************
* STATIC FUNCTIONS
**********************/
/**
* Open a file
* @param drv pointer to a driver where this function belongs
* @param path pointer to an extended path object containing the memory buffer address and size
* @param mode read: FS_MODE_RD (currently only reading from the buffer is supported)
* @return pointer to FIL struct or NULL in case of fail
*/
static void * fs_open(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode)
{
LV_UNUSED(drv);
LV_UNUSED(mode);
return (void *)path;
}
/**
* Close an opened file
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable. (opened with fs_open)
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_close(lv_fs_drv_t * drv, void * file_p)
{
LV_UNUSED(drv);
LV_UNUSED(file_p);
return LV_FS_RES_OK;
}
/**
* Read data from an opened file
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable.
* @param buf pointer to a memory block where to store the read data
* @param btr number of Bytes To Read
* @param br the real number of read bytes (Byte Read)
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_read(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br)
{
LV_UNUSED(drv);
LV_UNUSED(file_p);
LV_UNUSED(buf);
LV_UNUSED(btr);
*br = 0;
return LV_FS_RES_OK;
}
/**
* Set the read pointer.
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable. (opened with fs_open )
* @param pos the new position of read pointer
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_seek(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t whence)
{
/* NOTE: this function is only called to determine the end of the buffer when LV_FS_SEEK_END was given to lv_fs_seek() */
LV_UNUSED(drv);
lv_fs_file_t * fp = (lv_fs_file_t *)file_p;
switch(whence) {
case LV_FS_SEEK_SET: {
fp->cache->file_position = pos;
break;
}
case LV_FS_SEEK_CUR: {
fp->cache->file_position += pos;
break;
}
case LV_FS_SEEK_END: {
fp->cache->file_position = fp->cache->end - pos;
break;
}
}
if(fp->cache->file_position < fp->cache->start)
fp->cache->file_position = fp->cache->start;
else if(fp->cache->file_position > fp->cache->end)
fp->cache->file_position = fp->cache->end;
return LV_FS_RES_OK;
}
/**
* Give the position of the read write pointer
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable.
* @param pos_p pointer to to store the result
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_tell(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p)
{
LV_UNUSED(drv);
*pos_p = ((lv_fs_file_t *)file_p)->cache->file_position;
return LV_FS_RES_OK;
}
#else /*LV_USE_FS_MEMFS == 0*/
#if defined(LV_FS_MEMFS_LETTER) && LV_FS_MEMFS_LETTER != '\0'
#warning "LV_USE_FS_MEMFS is not enabled but LV_FS_MEMFS_LETTER is set"
#endif
#endif /*LV_USE_FS_MEMFS*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/fsdrv/lv_fsdrv.h | /**
* @file lv_fsdrv.h
*
*/
#ifndef LV_FSDRV_H
#define LV_FSDRV_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../lv_conf_internal.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
#if LV_USE_FS_FATFS
void lv_fs_fatfs_init(void);
#endif
#if LV_USE_FS_STDIO
void lv_fs_stdio_init(void);
#endif
#if LV_USE_FS_POSIX
void lv_fs_posix_init(void);
#endif
#if LV_USE_FS_WIN32
void lv_fs_win32_init(void);
#endif
#if LV_USE_FS_MEMFS
void lv_fs_memfs_init(void);
#endif
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*LV_FSDRV_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/fsdrv/lv_fs_stdio.c | /**
* @file lv_fs_stdio.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_FS_STDIO != '\0'
#include <stdio.h>
#ifndef WIN32
#include <dirent.h>
#include <unistd.h>
#else
#include <windows.h>
#endif
#include "../../core/lv_global.h"
/*********************
* DEFINES
*********************/
#define MAX_PATH_LEN 256
/**********************
* TYPEDEFS
**********************/
typedef struct {
#ifdef WIN32
HANDLE dir_p;
char next_fn[MAX_PATH_LEN];
#else
DIR * dir_p;
#endif
} dir_handle_t;
/**********************
* STATIC PROTOTYPES
**********************/
static void * fs_open(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode);
static lv_fs_res_t fs_close(lv_fs_drv_t * drv, void * file_p);
static lv_fs_res_t fs_read(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br);
static lv_fs_res_t fs_write(lv_fs_drv_t * drv, void * file_p, const void * buf, uint32_t btw, uint32_t * bw);
static lv_fs_res_t fs_seek(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t whence);
static lv_fs_res_t fs_tell(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p);
static void * fs_dir_open(lv_fs_drv_t * drv, const char * path);
static lv_fs_res_t fs_dir_read(lv_fs_drv_t * drv, void * dir_p, char * fn);
static lv_fs_res_t fs_dir_close(lv_fs_drv_t * drv, void * dir_p);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Register a driver for the File system interface
*/
void lv_fs_stdio_init(void)
{
/*---------------------------------------------------
* Register the file system interface in LVGL
*--------------------------------------------------*/
/*Add a simple drive to open images*/
lv_fs_drv_t * fs_drv_p = &(LV_GLOBAL_DEFAULT()->stdio_fs_drv);
lv_fs_drv_init(fs_drv_p);
/*Set up fields...*/
fs_drv_p->letter = LV_FS_STDIO_LETTER;
fs_drv_p->cache_size = LV_FS_STDIO_CACHE_SIZE;
fs_drv_p->open_cb = fs_open;
fs_drv_p->close_cb = fs_close;
fs_drv_p->read_cb = fs_read;
fs_drv_p->write_cb = fs_write;
fs_drv_p->seek_cb = fs_seek;
fs_drv_p->tell_cb = fs_tell;
fs_drv_p->dir_close_cb = fs_dir_close;
fs_drv_p->dir_open_cb = fs_dir_open;
fs_drv_p->dir_read_cb = fs_dir_read;
lv_fs_drv_register(fs_drv_p);
}
/**********************
* STATIC FUNCTIONS
**********************/
/**
* Open a file
* @param drv pointer to a driver where this function belongs
* @param path path to the file beginning with the driver letter (e.g. S:/folder/file.txt)
* @param mode read: FS_MODE_RD, write: FS_MODE_WR, both: FS_MODE_RD | FS_MODE_WR
* @return pointer to FIL struct or NULL in case of fail
*/
static void * fs_open(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode)
{
LV_UNUSED(drv);
const char * flags = "";
if(mode == LV_FS_MODE_WR) flags = "wb";
else if(mode == LV_FS_MODE_RD) flags = "rb";
else if(mode == (LV_FS_MODE_WR | LV_FS_MODE_RD)) flags = "rb+";
/*Make the path relative to the current directory (the projects root folder)*/
char buf[MAX_PATH_LEN];
lv_snprintf(buf, sizeof(buf), LV_FS_STDIO_PATH "%s", path);
return fopen(buf, flags);
}
/**
* Close an opened file
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable. (opened with fs_open)
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_close(lv_fs_drv_t * drv, void * file_p)
{
LV_UNUSED(drv);
fclose(file_p);
return LV_FS_RES_OK;
}
/**
* Read data from an opened file
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable.
* @param buf pointer to a memory block where to store the read data
* @param btr number of Bytes To Read
* @param br the real number of read bytes (Byte Read)
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_read(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br)
{
LV_UNUSED(drv);
*br = fread(buf, 1, btr, file_p);
return (int32_t)(*br) < 0 ? LV_FS_RES_UNKNOWN : LV_FS_RES_OK;
}
/**
* Write into a file
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable
* @param buf pointer to a buffer with the bytes to write
* @param btw Bytes To Write
* @param bw the number of real written bytes (Bytes Written). NULL if unused.
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_write(lv_fs_drv_t * drv, void * file_p, const void * buf, uint32_t btw, uint32_t * bw)
{
LV_UNUSED(drv);
*bw = fwrite(buf, 1, btw, file_p);
return (int32_t)(*bw) < 0 ? LV_FS_RES_UNKNOWN : LV_FS_RES_OK;
}
/**
* Set the read write pointer. Also expand the file size if necessary.
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable. (opened with fs_open )
* @param pos the new position of read write pointer
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_seek(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t whence)
{
LV_UNUSED(drv);
int w;
switch(whence) {
case LV_FS_SEEK_SET:
w = SEEK_SET;
break;
case LV_FS_SEEK_CUR:
w = SEEK_CUR;
break;
case LV_FS_SEEK_END:
w = SEEK_END;
break;
default:
return LV_FS_RES_INV_PARAM;
}
fseek(file_p, pos, w);
return LV_FS_RES_OK;
}
/**
* Give the position of the read write pointer
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable.
* @param pos_p pointer to to store the result
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_tell(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p)
{
LV_UNUSED(drv);
*pos_p = ftell(file_p);
return LV_FS_RES_OK;
}
/**
* Initialize a 'DIR' or 'HANDLE' variable for directory reading
* @param drv pointer to a driver where this function belongs
* @param path path to a directory
* @return pointer to an initialized 'DIR' or 'HANDLE' variable
*/
static void * fs_dir_open(lv_fs_drv_t * drv, const char * path)
{
LV_UNUSED(drv);
dir_handle_t * handle = (dir_handle_t *)lv_malloc(sizeof(dir_handle_t));
#ifndef WIN32
/*Make the path relative to the current directory (the projects root folder)*/
char buf[MAX_PATH_LEN];
lv_snprintf(buf, sizeof(buf), LV_FS_STDIO_PATH "%s", path);
handle->dir_p = opendir(buf);
if(handle->dir_p == NULL) {
lv_free(handle);
return NULL;
}
return handle;
#else
handle->dir_p = INVALID_HANDLE_VALUE;
WIN32_FIND_DATAA fdata;
/*Make the path relative to the current directory (the projects root folder)*/
char buf[MAX_PATH_LEN];
lv_snprintf(buf, sizeof(buf), LV_FS_STDIO_PATH "%s\\*", path);
lv_strcpy(handle->next_fn, "");
handle->dir_p = FindFirstFileA(buf, &fdata);
do {
if(strcmp(fdata.cFileName, ".") == 0 || strcmp(fdata.cFileName, "..") == 0) {
continue;
}
else {
if(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
lv_snprintf(handle->next_fn, sizeof(handle->next_fn), "/%s", fdata.cFileName);
}
else {
lv_snprintf(handle->next_fn, sizeof(handle->next_fn), "%s", fdata.cFileName);
}
break;
}
} while(FindNextFileA(handle->dir_p, &fdata));
if(handle->dir_p == INVALID_HANDLE_VALUE) {
lv_free(handle);
return INVALID_HANDLE_VALUE;
}
return handle;
#endif
}
/**
* Read the next filename form a directory.
* The name of the directories will begin with '/'
* @param drv pointer to a driver where this function belongs
* @param dir_p pointer to an initialized 'DIR' or 'HANDLE' variable
* @param fn pointer to a buffer to store the filename
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_dir_read(lv_fs_drv_t * drv, void * dir_p, char * fn)
{
LV_UNUSED(drv);
dir_handle_t * handle = (dir_handle_t *)dir_p;
#ifndef WIN32
struct dirent * entry;
do {
entry = readdir(handle->dir_p);
if(entry) {
if(entry->d_type == DT_DIR) snprintf(fn, strlen(entry->d_name), "/%s", entry->d_name);
else lv_strcpy(fn, entry->d_name);
}
else {
lv_strcpy(fn, "");
}
} while(strcmp(fn, "/.") == 0 || strcmp(fn, "/..") == 0);
#else
lv_strcpy(fn, handle->next_fn);
lv_strcpy(handle->next_fn, "");
WIN32_FIND_DATAA fdata;
if(FindNextFileA(handle->dir_p, &fdata) == false) return LV_FS_RES_OK;
do {
if(strcmp(fdata.cFileName, ".") == 0 || strcmp(fdata.cFileName, "..") == 0) {
continue;
}
else {
if(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
lv_snprintf(handle->next_fn, sizeof(handle->next_fn), "/%s", fdata.cFileName);
}
else {
lv_snprintf(handle->next_fn, sizeof(handle->next_fn), "%s", fdata.cFileName);
}
break;
}
} while(FindNextFileA(handle->dir_p, &fdata));
#endif
return LV_FS_RES_OK;
}
/**
* Close the directory reading
* @param drv pointer to a driver where this function belongs
* @param dir_p pointer to an initialized 'DIR' or 'HANDLE' variable
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_dir_close(lv_fs_drv_t * drv, void * dir_p)
{
LV_UNUSED(drv);
dir_handle_t * handle = (dir_handle_t *)dir_p;
#ifndef WIN32
closedir(handle->dir_p);
#else
FindClose(handle->dir_p);
#endif
lv_free(handle);
return LV_FS_RES_OK;
}
#else /*LV_USE_FS_STDIO == 0*/
#if defined(LV_FS_STDIO_LETTER) && LV_FS_STDIO_LETTER != '\0'
#warning "LV_USE_FS_STDIO is not enabled but LV_FS_STDIO_LETTER is set"
#endif
#endif /*LV_USE_FS_POSIX*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/fsdrv/lv_fs_fatfs.c | /**
* @file lv_fs_fatfs.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_FS_FATFS
#include "ff.h"
#include "../../core/lv_global.h"
/*********************
* DEFINES
*********************/
#if LV_FS_FATFS_LETTER == '\0'
#error "LV_FS_FATFS_LETTER must be an upper case ASCII letter"
#endif
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void fs_init(void);
static void * fs_open(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode);
static lv_fs_res_t fs_close(lv_fs_drv_t * drv, void * file_p);
static lv_fs_res_t fs_read(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br);
static lv_fs_res_t fs_write(lv_fs_drv_t * drv, void * file_p, const void * buf, uint32_t btw, uint32_t * bw);
static lv_fs_res_t fs_seek(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t whence);
static lv_fs_res_t fs_tell(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p);
static void * fs_dir_open(lv_fs_drv_t * drv, const char * path);
static lv_fs_res_t fs_dir_read(lv_fs_drv_t * drv, void * dir_p, char * fn);
static lv_fs_res_t fs_dir_close(lv_fs_drv_t * drv, void * dir_p);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_fs_fatfs_init(void)
{
/*----------------------------------------------------
* Initialize your storage device and File System
* -------------------------------------------------*/
fs_init();
/*---------------------------------------------------
* Register the file system interface in LVGL
*--------------------------------------------------*/
/*Add a simple drive to open images*/
lv_fs_drv_t * fs_drv_p = &(LV_GLOBAL_DEFAULT()->fatfs_fs_drv);
lv_fs_drv_init(fs_drv_p);
/*Set up fields...*/
fs_drv_p->letter = LV_FS_FATFS_LETTER;
fs_drv_p->cache_size = LV_FS_FATFS_CACHE_SIZE;
fs_drv_p->open_cb = fs_open;
fs_drv_p->close_cb = fs_close;
fs_drv_p->read_cb = fs_read;
fs_drv_p->write_cb = fs_write;
fs_drv_p->seek_cb = fs_seek;
fs_drv_p->tell_cb = fs_tell;
fs_drv_p->dir_close_cb = fs_dir_close;
fs_drv_p->dir_open_cb = fs_dir_open;
fs_drv_p->dir_read_cb = fs_dir_read;
lv_fs_drv_register(fs_drv_p);
}
/**********************
* STATIC FUNCTIONS
**********************/
/*Initialize your Storage device and File system.*/
static void fs_init(void)
{
/*Initialize the SD card and FatFS itself.
*Better to do it in your code to keep this library untouched for easy updating*/
}
/**
* Open a file
* @param drv pointer to a driver where this function belongs
* @param path path to the file beginning with the driver letter (e.g. S:/folder/file.txt)
* @param mode read: FS_MODE_RD, write: FS_MODE_WR, both: FS_MODE_RD | FS_MODE_WR
* @return pointer to FIL struct or NULL in case of fail
*/
static void * fs_open(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode)
{
LV_UNUSED(drv);
uint8_t flags = 0;
if(mode == LV_FS_MODE_WR) flags = FA_WRITE | FA_OPEN_ALWAYS;
else if(mode == LV_FS_MODE_RD) flags = FA_READ;
else if(mode == (LV_FS_MODE_WR | LV_FS_MODE_RD)) flags = FA_READ | FA_WRITE | FA_OPEN_ALWAYS;
FIL * f = lv_malloc(sizeof(FIL));
if(f == NULL) return NULL;
FRESULT res = f_open(f, path, flags);
if(res == FR_OK) {
return f;
}
else {
lv_free(f);
return NULL;
}
}
/**
* Close an opened file
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FIL variable. (opened with fs_open)
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_close(lv_fs_drv_t * drv, void * file_p)
{
LV_UNUSED(drv);
f_close(file_p);
lv_free(file_p);
return LV_FS_RES_OK;
}
/**
* Read data from an opened file
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FIL variable.
* @param buf pointer to a memory block where to store the read data
* @param btr number of Bytes To Read
* @param br the real number of read bytes (Byte Read)
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_read(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br)
{
LV_UNUSED(drv);
FRESULT res = f_read(file_p, buf, btr, (UINT *)br);
if(res == FR_OK) return LV_FS_RES_OK;
else return LV_FS_RES_UNKNOWN;
}
/**
* Write into a file
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FIL variable
* @param buf pointer to a buffer with the bytes to write
* @param btw Bytes To Write
* @param bw the number of real written bytes (Bytes Written). NULL if unused.
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_write(lv_fs_drv_t * drv, void * file_p, const void * buf, uint32_t btw, uint32_t * bw)
{
LV_UNUSED(drv);
FRESULT res = f_write(file_p, buf, btw, (UINT *)bw);
if(res == FR_OK) return LV_FS_RES_OK;
else return LV_FS_RES_UNKNOWN;
}
/**
* Set the read write pointer. Also expand the file size if necessary.
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FIL variable. (opened with fs_open )
* @param pos the new position of read write pointer
* @param whence only LV_SEEK_SET is supported
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_seek(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t whence)
{
LV_UNUSED(drv);
switch(whence) {
case LV_FS_SEEK_SET:
f_lseek(file_p, pos);
break;
case LV_FS_SEEK_CUR:
f_lseek(file_p, f_tell((FIL *)file_p) + pos);
break;
case LV_FS_SEEK_END:
f_lseek(file_p, f_size((FIL *)file_p) + pos);
break;
default:
break;
}
return LV_FS_RES_OK;
}
/**
* Give the position of the read write pointer
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FIL variable.
* @param pos_p pointer to to store the result
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_tell(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p)
{
LV_UNUSED(drv);
*pos_p = f_tell((FIL *)file_p);
return LV_FS_RES_OK;
}
/**
* Initialize a 'DIR' variable for directory reading
* @param drv pointer to a driver where this function belongs
* @param path path to a directory
* @return pointer to an initialized 'DIR' variable
*/
static void * fs_dir_open(lv_fs_drv_t * drv, const char * path)
{
LV_UNUSED(drv);
DIR * d = lv_malloc(sizeof(DIR));
if(d == NULL) return NULL;
FRESULT res = f_opendir(d, path);
if(res != FR_OK) {
lv_free(d);
d = NULL;
}
return d;
}
/**
* Read the next filename from a directory.
* The name of the directories will begin with '/'
* @param drv pointer to a driver where this function belongs
* @param dir_p pointer to an initialized 'DIR' variable
* @param fn pointer to a buffer to store the filename
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_dir_read(lv_fs_drv_t * drv, void * dir_p, char * fn)
{
LV_UNUSED(drv);
FRESULT res;
FILINFO fno;
fn[0] = '\0';
do {
res = f_readdir(dir_p, &fno);
if(res != FR_OK) return LV_FS_RES_UNKNOWN;
if(fno.fattrib & AM_DIR) {
fn[0] = '/';
lv_strcpy(&fn[1], fno.fname);
}
else lv_strcpy(fn, fno.fname);
} while(strcmp(fn, "/.") == 0 || strcmp(fn, "/..") == 0);
return LV_FS_RES_OK;
}
/**
* Close the directory reading
* @param drv pointer to a driver where this function belongs
* @param dir_p pointer to an initialized 'DIR' variable
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_dir_close(lv_fs_drv_t * drv, void * dir_p)
{
LV_UNUSED(drv);
f_closedir(dir_p);
lv_free(dir_p);
return LV_FS_RES_OK;
}
#else /*LV_USE_FS_FATFS == 0*/
#if defined(LV_FS_FATFS_LETTER) && LV_FS_FATFS_LETTER != '\0'
#warning "LV_USE_FS_FATFS is not enabled but LV_FS_FATFS_LETTER is set"
#endif
#endif /*LV_USE_FS_POSIX*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/fsdrv/lv_fs_win32.c | /**
* @file lv_fs_win32.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_FS_WIN32 != '\0'
#include <windows.h>
#include <stdio.h>
#include <limits.h>
#include "../../core/lv_global.h"
/*********************
* DEFINES
*********************/
#define MAX_PATH_LEN 256
/**********************
* TYPEDEFS
**********************/
typedef struct {
HANDLE dir_p;
char next_fn[MAX_PATH_LEN];
lv_fs_res_t next_error;
} dir_handle_t;
/**********************
* STATIC PROTOTYPES
**********************/
static bool is_dots_name(const char * name);
static lv_fs_res_t fs_error_from_win32(DWORD error);
static void * fs_open(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode);
static lv_fs_res_t fs_close(lv_fs_drv_t * drv, void * file_p);
static lv_fs_res_t fs_read(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br);
static lv_fs_res_t fs_write(lv_fs_drv_t * drv, void * file_p, const void * buf, uint32_t btw, uint32_t * bw);
static lv_fs_res_t fs_seek(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t whence);
static lv_fs_res_t fs_tell(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p);
static void * fs_dir_open(lv_fs_drv_t * drv, const char * path);
static lv_fs_res_t fs_dir_read(lv_fs_drv_t * drv, void * dir_p, char * fn);
static lv_fs_res_t fs_dir_close(lv_fs_drv_t * drv, void * dir_p);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Register a driver for the File system interface
*/
void lv_fs_win32_init(void)
{
/*---------------------------------------------------
* Register the file system interface in LVGL
*--------------------------------------------------*/
/*Add a simple driver to open images*/
lv_fs_drv_t * fs_drv_p = &(LV_GLOBAL_DEFAULT()->win32_fs_drv);
lv_fs_drv_init(fs_drv_p);
/*Set up fields...*/
fs_drv_p->letter = LV_FS_WIN32_LETTER;
fs_drv_p->cache_size = LV_FS_WIN32_CACHE_SIZE;
fs_drv_p->open_cb = fs_open;
fs_drv_p->close_cb = fs_close;
fs_drv_p->read_cb = fs_read;
fs_drv_p->write_cb = fs_write;
fs_drv_p->seek_cb = fs_seek;
fs_drv_p->tell_cb = fs_tell;
fs_drv_p->dir_close_cb = fs_dir_close;
fs_drv_p->dir_open_cb = fs_dir_open;
fs_drv_p->dir_read_cb = fs_dir_read;
lv_fs_drv_register(fs_drv_p);
}
/**********************
* STATIC FUNCTIONS
**********************/
/**
* Check the dots name
* @param name file or dir name
* @return true if the name is dots name
*/
static bool is_dots_name(const char * name)
{
return name[0] == '.' && (!name[1] || (name[1] == '.' && !name[2]));
}
/**
* Convert Win32 error code to error from lv_fs_res_t enum
* @param error Win32 error code
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_error_from_win32(DWORD error)
{
lv_fs_res_t res;
switch(error) {
case ERROR_SUCCESS:
res = LV_FS_RES_OK;
break;
case ERROR_BAD_UNIT:
case ERROR_NOT_READY:
case ERROR_CRC:
case ERROR_SEEK:
case ERROR_NOT_DOS_DISK:
case ERROR_WRITE_FAULT:
case ERROR_READ_FAULT:
case ERROR_GEN_FAILURE:
case ERROR_WRONG_DISK:
res = LV_FS_RES_HW_ERR;
break;
case ERROR_INVALID_HANDLE:
case ERROR_INVALID_TARGET_HANDLE:
res = LV_FS_RES_FS_ERR;
break;
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND:
case ERROR_INVALID_DRIVE:
case ERROR_NO_MORE_FILES:
case ERROR_SECTOR_NOT_FOUND:
case ERROR_BAD_NETPATH:
case ERROR_BAD_NET_NAME:
case ERROR_BAD_PATHNAME:
case ERROR_FILENAME_EXCED_RANGE:
res = LV_FS_RES_NOT_EX;
break;
case ERROR_DISK_FULL:
res = LV_FS_RES_FULL;
break;
case ERROR_SHARING_VIOLATION:
case ERROR_LOCK_VIOLATION:
case ERROR_DRIVE_LOCKED:
res = LV_FS_RES_LOCKED;
break;
case ERROR_ACCESS_DENIED:
case ERROR_CURRENT_DIRECTORY:
case ERROR_WRITE_PROTECT:
case ERROR_NETWORK_ACCESS_DENIED:
case ERROR_CANNOT_MAKE:
case ERROR_FAIL_I24:
case ERROR_SEEK_ON_DEVICE:
case ERROR_NOT_LOCKED:
case ERROR_LOCK_FAILED:
res = LV_FS_RES_DENIED;
break;
case ERROR_BUSY:
res = LV_FS_RES_BUSY;
break;
case ERROR_TIMEOUT:
res = LV_FS_RES_TOUT;
break;
case ERROR_NOT_SAME_DEVICE:
case ERROR_DIRECT_ACCESS_HANDLE:
res = LV_FS_RES_NOT_IMP;
break;
case ERROR_TOO_MANY_OPEN_FILES:
case ERROR_ARENA_TRASHED:
case ERROR_NOT_ENOUGH_MEMORY:
case ERROR_INVALID_BLOCK:
case ERROR_OUT_OF_PAPER:
case ERROR_SHARING_BUFFER_EXCEEDED:
case ERROR_NOT_ENOUGH_QUOTA:
res = LV_FS_RES_OUT_OF_MEM;
break;
case ERROR_INVALID_FUNCTION:
case ERROR_INVALID_ACCESS:
case ERROR_INVALID_DATA:
case ERROR_BAD_COMMAND:
case ERROR_BAD_LENGTH:
case ERROR_INVALID_PARAMETER:
case ERROR_NEGATIVE_SEEK:
res = LV_FS_RES_INV_PARAM;
break;
default:
res = LV_FS_RES_UNKNOWN;
break;
}
return res;
}
/**
* Open a file
* @param drv pointer to a driver where this function belongs
* @param path path to the file beginning with the driver letter (e.g. S:/folder/file.txt)
* @param mode read: FS_MODE_RD, write: FS_MODE_WR, both: FS_MODE_RD | FS_MODE_WR
* @return pointer to FIL struct or NULL in case of fail
*/
static void * fs_open(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode)
{
LV_UNUSED(drv);
DWORD desired_access = 0;
if(mode & LV_FS_MODE_RD) {
desired_access |= GENERIC_READ;
}
if(mode & LV_FS_MODE_WR) {
desired_access |= GENERIC_WRITE;
}
/*Make the path relative to the current directory (the projects root folder)*/
char buf[MAX_PATH];
lv_snprintf(buf, sizeof(buf), LV_FS_WIN32_PATH "%s", path);
return (void *)CreateFileA(
buf,
desired_access,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
}
/**
* Close an opened file
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable. (opened with fs_open)
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_close(lv_fs_drv_t * drv, void * file_p)
{
LV_UNUSED(drv);
return CloseHandle((HANDLE)file_p)
? LV_FS_RES_OK
: fs_error_from_win32(GetLastError());
}
/**
* Read data from an opened file
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable.
* @param buf pointer to a memory block where to store the read data
* @param btr number of Bytes To Read
* @param br the real number of read bytes (Byte Read)
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_read(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br)
{
LV_UNUSED(drv);
return ReadFile((HANDLE)file_p, buf, btr, (LPDWORD)br, NULL)
? LV_FS_RES_OK
: fs_error_from_win32(GetLastError());
}
/**
* Write into a file
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable
* @param buf pointer to a buffer with the bytes to write
* @param btw Bytes To Write
* @param bw the number of real written bytes (Bytes Written). NULL if unused.
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_write(lv_fs_drv_t * drv, void * file_p, const void * buf, uint32_t btw, uint32_t * bw)
{
LV_UNUSED(drv);
return WriteFile((HANDLE)file_p, buf, btw, (LPDWORD)bw, NULL)
? LV_FS_RES_OK
: fs_error_from_win32(GetLastError());
}
/**
* Set the read write pointer. Also expand the file size if necessary.
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable. (opened with fs_open )
* @param pos the new position of read write pointer
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_seek(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t whence)
{
LV_UNUSED(drv);
DWORD move_method = (DWORD) -1;
if(whence == LV_FS_SEEK_SET) {
move_method = FILE_BEGIN;
}
else if(whence == LV_FS_SEEK_CUR) {
move_method = FILE_CURRENT;
}
else if(whence == LV_FS_SEEK_END) {
move_method = FILE_END;
}
LARGE_INTEGER distance_to_move;
distance_to_move.QuadPart = pos;
return SetFilePointerEx((HANDLE)file_p, distance_to_move, NULL, move_method)
? LV_FS_RES_OK
: fs_error_from_win32(GetLastError());
}
/**
* Give the position of the read write pointer
* @param drv pointer to a driver where this function belongs
* @param file_p pointer to a FILE variable.
* @param pos_p pointer to to store the result
* @return LV_FS_RES_OK: no error, the file is read
* any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_tell(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p)
{
LV_UNUSED(drv);
if(!pos_p) {
return LV_FS_RES_INV_PARAM;
}
LARGE_INTEGER file_pointer;
file_pointer.QuadPart = 0;
LARGE_INTEGER distance_to_move;
distance_to_move.QuadPart = 0;
if(SetFilePointerEx(
(HANDLE)file_p,
distance_to_move,
&file_pointer,
FILE_CURRENT)) {
if(file_pointer.QuadPart > LONG_MAX) {
return LV_FS_RES_INV_PARAM;
}
else {
*pos_p = file_pointer.LowPart;
return LV_FS_RES_OK;
}
}
else {
return fs_error_from_win32(GetLastError());
}
}
/**
* Initialize a 'DIR' or 'HANDLE' variable for directory reading
* @param drv pointer to a driver where this function belongs
* @param path path to a directory
* @return pointer to an initialized 'DIR' or 'HANDLE' variable
*/
static void * fs_dir_open(lv_fs_drv_t * drv, const char * path)
{
LV_UNUSED(drv);
dir_handle_t * handle = (dir_handle_t *)lv_malloc(sizeof(dir_handle_t));
handle->dir_p = INVALID_HANDLE_VALUE;
handle->next_error = LV_FS_RES_OK;
WIN32_FIND_DATAA fdata;
/*Make the path relative to the current directory (the projects root folder)*/
char buf[MAX_PATH_LEN];
#ifdef LV_FS_WIN32_PATH
lv_snprintf(buf, sizeof(buf), LV_FS_WIN32_PATH "%s\\*", path);
#else
lv_snprintf(buf, sizeof(buf), "%s\\*", path);
#endif
lv_strcpy(handle->next_fn, "");
handle->dir_p = FindFirstFileA(buf, &fdata);
do {
if(is_dots_name(fdata.cFileName)) {
continue;
}
else {
if(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
lv_snprintf(handle->next_fn, sizeof(handle->next_fn), "/%s", fdata.cFileName);
}
else {
lv_snprintf(handle->next_fn, sizeof(handle->next_fn), "%s", fdata.cFileName);
}
break;
}
} while(FindNextFileA(handle->dir_p, &fdata));
if(handle->dir_p == INVALID_HANDLE_VALUE) {
lv_free(handle);
handle->next_error = fs_error_from_win32(GetLastError());
return INVALID_HANDLE_VALUE;
}
else {
handle->next_error = LV_FS_RES_OK;
return handle;
}
}
/**
* Read the next filename from a directory.
* The name of the directories will begin with '/'
* @param drv pointer to a driver where this function belongs
* @param dir_p pointer to an initialized 'DIR' or 'HANDLE' variable
* @param fn pointer to a buffer to store the filename
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_dir_read(lv_fs_drv_t * drv, void * dir_p, char * fn)
{
LV_UNUSED(drv);
dir_handle_t * handle = (dir_handle_t *)dir_p;
lv_strcpy(fn, handle->next_fn);
lv_fs_res_t current_error = handle->next_error;
lv_strcpy(handle->next_fn, "");
WIN32_FIND_DATAA fdata;
while(FindNextFileA(handle->dir_p, &fdata)) {
if(is_dots_name(fdata.cFileName)) {
continue;
}
else {
if(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
lv_snprintf(handle->next_fn, sizeof(handle->next_fn), "/%s", fdata.cFileName);
}
else {
lv_snprintf(handle->next_fn, sizeof(handle->next_fn), "%s", fdata.cFileName);
}
break;
}
}
if(handle->next_fn[0] == '\0') {
handle->next_error = fs_error_from_win32(GetLastError());
}
return current_error;
}
/**
* Close the directory reading
* @param drv pointer to a driver where this function belongs
* @param dir_p pointer to an initialized 'DIR' or 'HANDLE' variable
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
*/
static lv_fs_res_t fs_dir_close(lv_fs_drv_t * drv, void * dir_p)
{
LV_UNUSED(drv);
dir_handle_t * handle = (dir_handle_t *)dir_p;
lv_fs_res_t res = FindClose(handle->dir_p)
? LV_FS_RES_OK
: fs_error_from_win32(GetLastError());
lv_free(handle);
return res;
}
#else /*LV_USE_FS_WIN32 == 0*/
#if defined(LV_FS_WIN32_LETTER) && LV_FS_WIN32_LETTER != '\0'
#warning "LV_USE_FS_WIN32 is not enabled but LV_FS_WIN32_LETTER is set"
#endif
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/ffmpeg/lv_ffmpeg.h | /**
* @file lv_ffmpeg.h
*
*/
#ifndef LV_FFMPEG_H
#define LV_FFMPEG_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_FFMPEG != 0
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
struct ffmpeg_context_s;
extern const lv_obj_class_t lv_ffmpeg_player_class;
typedef struct {
lv_image_t img;
lv_timer_t * timer;
lv_image_dsc_t imgdsc;
bool auto_restart;
struct ffmpeg_context_s * ffmpeg_ctx;
} lv_ffmpeg_player_t;
typedef enum {
LV_FFMPEG_PLAYER_CMD_START,
LV_FFMPEG_PLAYER_CMD_STOP,
LV_FFMPEG_PLAYER_CMD_PAUSE,
LV_FFMPEG_PLAYER_CMD_RESUME,
_LV_FFMPEG_PLAYER_CMD_LAST
} lv_ffmpeg_player_cmd_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Register FFMPEG image decoder
*/
void lv_ffmpeg_init(void);
/**
* Get the number of frames contained in the file
* @param path image or video file name
* @return Number of frames, less than 0 means failed
*/
int lv_ffmpeg_get_frame_num(const char * path);
/**
* Create ffmpeg_player object
* @param parent pointer to an object, it will be the parent of the new player
* @return pointer to the created ffmpeg_player
*/
lv_obj_t * lv_ffmpeg_player_create(lv_obj_t * parent);
/**
* Set the path of the file to be played
* @param obj pointer to a ffmpeg_player object
* @param path video file path
* @return LV_RESULT_OK: no error; LV_RESULT_INVALID: can't get the info.
*/
lv_result_t lv_ffmpeg_player_set_src(lv_obj_t * obj, const char * path);
/**
* Set command control video player
* @param obj pointer to a ffmpeg_player object
* @param cmd control commands
*/
void lv_ffmpeg_player_set_cmd(lv_obj_t * obj, lv_ffmpeg_player_cmd_t cmd);
/**
* Set the video to automatically replay
* @param obj pointer to a ffmpeg_player object
* @param en true: enable the auto restart
*/
void lv_ffmpeg_player_set_auto_restart(lv_obj_t * obj, bool en);
/*=====================
* Other functions
*====================*/
/**********************
* MACROS
**********************/
#endif /*LV_USE_FFMPEG*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_FFMPEG_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/ffmpeg/lv_ffmpeg.c | /**
* @file lv_ffmpeg.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_ffmpeg.h"
#if LV_USE_FFMPEG != 0
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libavutil/samplefmt.h>
#include <libavutil/timestamp.h>
#include <libswscale/swscale.h>
/*********************
* DEFINES
*********************/
#if LV_COLOR_DEPTH == 8
#define AV_PIX_FMT_TRUE_COLOR AV_PIX_FMT_RGB8
#elif LV_COLOR_DEPTH == 16
#define AV_PIX_FMT_TRUE_COLOR AV_PIX_FMT_RGB565LE
#elif LV_COLOR_DEPTH == 32
#define AV_PIX_FMT_TRUE_COLOR AV_PIX_FMT_BGR0
#else
#error Unsupported LV_COLOR_DEPTH
#endif
#define MY_CLASS &lv_ffmpeg_player_class
#define FRAME_DEF_REFR_PERIOD 33 /*[ms]*/
/**********************
* TYPEDEFS
**********************/
struct ffmpeg_context_s {
AVFormatContext * fmt_ctx;
AVCodecContext * video_dec_ctx;
AVStream * video_stream;
uint8_t * video_src_data[4];
uint8_t * video_dst_data[4];
struct SwsContext * sws_ctx;
AVFrame * frame;
AVPacket * pkt;
int video_stream_idx;
int video_src_linesize[4];
int video_dst_linesize[4];
enum AVPixelFormat video_dst_pix_fmt;
bool has_alpha;
};
#pragma pack(1)
struct lv_image_pixel_color_s {
lv_color_t c;
uint8_t alpha;
};
#pragma pack()
/**********************
* STATIC PROTOTYPES
**********************/
static lv_result_t decoder_info(lv_image_decoder_t * decoder, const void * src, lv_image_header_t * header);
static lv_result_t decoder_open(lv_image_decoder_t * dec, lv_image_decoder_dsc_t * dsc);
static void decoder_close(lv_image_decoder_t * dec, lv_image_decoder_dsc_t * dsc);
static struct ffmpeg_context_s * ffmpeg_open_file(const char * path);
static void ffmpeg_close(struct ffmpeg_context_s * ffmpeg_ctx);
static void ffmpeg_close_src_ctx(struct ffmpeg_context_s * ffmpeg_ctx);
static void ffmpeg_close_dst_ctx(struct ffmpeg_context_s * ffmpeg_ctx);
static int ffmpeg_image_allocate(struct ffmpeg_context_s * ffmpeg_ctx);
static int ffmpeg_get_image_header(const char * path, lv_image_header_t * header);
static int ffmpeg_get_frame_refr_period(struct ffmpeg_context_s * ffmpeg_ctx);
static uint8_t * ffmpeg_get_image_data(struct ffmpeg_context_s * ffmpeg_ctx);
static int ffmpeg_update_next_frame(struct ffmpeg_context_s * ffmpeg_ctx);
static int ffmpeg_output_video_frame(struct ffmpeg_context_s * ffmpeg_ctx);
static bool ffmpeg_pix_fmt_has_alpha(enum AVPixelFormat pix_fmt);
static bool ffmpeg_pix_fmt_is_yuv(enum AVPixelFormat pix_fmt);
static void lv_ffmpeg_player_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_ffmpeg_player_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_ffmpeg_player_class = {
.constructor_cb = lv_ffmpeg_player_constructor,
.destructor_cb = lv_ffmpeg_player_destructor,
.instance_size = sizeof(lv_ffmpeg_player_t),
.base_class = &lv_image_class,
.name = "ffmpeg-player",
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_ffmpeg_init(void)
{
lv_image_decoder_t * dec = lv_image_decoder_create();
lv_image_decoder_set_info_cb(dec, decoder_info);
lv_image_decoder_set_open_cb(dec, decoder_open);
lv_image_decoder_set_close_cb(dec, decoder_close);
#if LV_FFMPEG_AV_DUMP_FORMAT == 0
av_log_set_level(AV_LOG_QUIET);
#endif
}
int lv_ffmpeg_get_frame_num(const char * path)
{
int ret = -1;
struct ffmpeg_context_s * ffmpeg_ctx = ffmpeg_open_file(path);
if(ffmpeg_ctx) {
ret = ffmpeg_ctx->video_stream->nb_frames;
ffmpeg_close(ffmpeg_ctx);
}
return ret;
}
lv_obj_t * lv_ffmpeg_player_create(lv_obj_t * parent)
{
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
lv_result_t lv_ffmpeg_player_set_src(lv_obj_t * obj, const char * path)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_result_t res = LV_RESULT_INVALID;
lv_ffmpeg_player_t * player = (lv_ffmpeg_player_t *)obj;
if(player->ffmpeg_ctx) {
ffmpeg_close(player->ffmpeg_ctx);
player->ffmpeg_ctx = NULL;
}
lv_timer_pause(player->timer);
player->ffmpeg_ctx = ffmpeg_open_file(path);
if(!player->ffmpeg_ctx) {
LV_LOG_ERROR("ffmpeg file open failed: %s", path);
goto failed;
}
if(ffmpeg_image_allocate(player->ffmpeg_ctx) < 0) {
LV_LOG_ERROR("ffmpeg image allocate failed");
ffmpeg_close(player->ffmpeg_ctx);
goto failed;
}
bool has_alpha = player->ffmpeg_ctx->has_alpha;
int width = player->ffmpeg_ctx->video_dec_ctx->width;
int height = player->ffmpeg_ctx->video_dec_ctx->height;
uint32_t data_size = 0;
data_size = width * height * 4;
player->imgdsc.header.always_zero = 0;
player->imgdsc.header.w = width;
player->imgdsc.header.h = height;
player->imgdsc.data_size = data_size;
player->imgdsc.header.cf = has_alpha ? LV_COLOR_FORMAT_ARGB8888 : LV_COLOR_FORMAT_NATIVE;
player->imgdsc.data = ffmpeg_get_image_data(player->ffmpeg_ctx);
lv_image_set_src(&player->img.obj, &(player->imgdsc));
int period = ffmpeg_get_frame_refr_period(player->ffmpeg_ctx);
if(period > 0) {
LV_LOG_INFO("frame refresh period = %d ms, rate = %d fps",
period, 1000 / period);
lv_timer_set_period(player->timer, period);
}
else {
LV_LOG_WARN("unable to get frame refresh period");
}
res = LV_RESULT_OK;
failed:
return res;
}
void lv_ffmpeg_player_set_cmd(lv_obj_t * obj, lv_ffmpeg_player_cmd_t cmd)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_ffmpeg_player_t * player = (lv_ffmpeg_player_t *)obj;
if(!player->ffmpeg_ctx) {
LV_LOG_ERROR("ffmpeg_ctx is NULL");
return;
}
lv_timer_t * timer = player->timer;
switch(cmd) {
case LV_FFMPEG_PLAYER_CMD_START:
av_seek_frame(player->ffmpeg_ctx->fmt_ctx,
0, 0, AVSEEK_FLAG_BACKWARD);
lv_timer_resume(timer);
LV_LOG_INFO("ffmpeg player start");
break;
case LV_FFMPEG_PLAYER_CMD_STOP:
av_seek_frame(player->ffmpeg_ctx->fmt_ctx,
0, 0, AVSEEK_FLAG_BACKWARD);
lv_timer_pause(timer);
LV_LOG_INFO("ffmpeg player stop");
break;
case LV_FFMPEG_PLAYER_CMD_PAUSE:
lv_timer_pause(timer);
LV_LOG_INFO("ffmpeg player pause");
break;
case LV_FFMPEG_PLAYER_CMD_RESUME:
lv_timer_resume(timer);
LV_LOG_INFO("ffmpeg player resume");
break;
default:
LV_LOG_ERROR("Error cmd: %d", cmd);
break;
}
}
void lv_ffmpeg_player_set_auto_restart(lv_obj_t * obj, bool en)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_ffmpeg_player_t * player = (lv_ffmpeg_player_t *)obj;
player->auto_restart = en;
}
/**********************
* STATIC FUNCTIONS
**********************/
static lv_result_t decoder_info(lv_image_decoder_t * decoder, const void * src, lv_image_header_t * header)
{
LV_UNUSED(decoder);
/* Get the source type */
lv_image_src_t src_type = lv_image_src_get_type(src);
if(src_type == LV_IMAGE_SRC_FILE) {
const char * fn = src;
if(ffmpeg_get_image_header(fn, header) < 0) {
LV_LOG_ERROR("ffmpeg can't get image header");
return LV_RESULT_INVALID;
}
return LV_RESULT_OK;
}
/* If didn't succeeded earlier then it's an error */
return LV_RESULT_INVALID;
}
static lv_result_t decoder_open(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder);
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
const char * path = dsc->src;
struct ffmpeg_context_s * ffmpeg_ctx = ffmpeg_open_file(path);
if(ffmpeg_ctx == NULL) {
return LV_RESULT_INVALID;
}
if(ffmpeg_image_allocate(ffmpeg_ctx) < 0) {
LV_LOG_ERROR("ffmpeg image allocate failed");
ffmpeg_close(ffmpeg_ctx);
return LV_RESULT_INVALID;
}
if(ffmpeg_update_next_frame(ffmpeg_ctx) < 0) {
ffmpeg_close(ffmpeg_ctx);
LV_LOG_ERROR("ffmpeg update frame failed");
return LV_RESULT_INVALID;
}
ffmpeg_close_src_ctx(ffmpeg_ctx);
uint8_t * img_data = ffmpeg_get_image_data(ffmpeg_ctx);
dsc->user_data = ffmpeg_ctx;
dsc->img_data = img_data;
/* The image is fully decoded. Return with its pointer */
return LV_RESULT_OK;
}
/* If not returned earlier then it failed */
return LV_RESULT_INVALID;
}
static void decoder_close(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder);
struct ffmpeg_context_s * ffmpeg_ctx = dsc->user_data;
ffmpeg_close(ffmpeg_ctx);
}
static uint8_t * ffmpeg_get_image_data(struct ffmpeg_context_s * ffmpeg_ctx)
{
uint8_t * img_data = ffmpeg_ctx->video_dst_data[0];
if(img_data == NULL) {
LV_LOG_ERROR("ffmpeg video dst data is NULL");
}
return img_data;
}
static bool ffmpeg_pix_fmt_has_alpha(enum AVPixelFormat pix_fmt)
{
const AVPixFmtDescriptor * desc = av_pix_fmt_desc_get(pix_fmt);
if(desc == NULL) {
return false;
}
if(pix_fmt == AV_PIX_FMT_PAL8) {
return true;
}
return desc->flags & AV_PIX_FMT_FLAG_ALPHA;
}
static bool ffmpeg_pix_fmt_is_yuv(enum AVPixelFormat pix_fmt)
{
const AVPixFmtDescriptor * desc = av_pix_fmt_desc_get(pix_fmt);
if(desc == NULL) {
return false;
}
return !(desc->flags & AV_PIX_FMT_FLAG_RGB) && desc->nb_components >= 2;
}
static int ffmpeg_output_video_frame(struct ffmpeg_context_s * ffmpeg_ctx)
{
int ret = -1;
int width = ffmpeg_ctx->video_dec_ctx->width;
int height = ffmpeg_ctx->video_dec_ctx->height;
AVFrame * frame = ffmpeg_ctx->frame;
if(frame->width != width
|| frame->height != height
|| frame->format != ffmpeg_ctx->video_dec_ctx->pix_fmt) {
/* To handle this change, one could call av_image_alloc again and
* decode the following frames into another rawvideo file.
*/
LV_LOG_ERROR("Width, height and pixel format have to be "
"constant in a rawvideo file, but the width, height or "
"pixel format of the input video changed:\n"
"old: width = %d, height = %d, format = %s\n"
"new: width = %d, height = %d, format = %s\n",
width,
height,
av_get_pix_fmt_name(ffmpeg_ctx->video_dec_ctx->pix_fmt),
frame->width, frame->height,
av_get_pix_fmt_name(frame->format));
goto failed;
}
LV_LOG_TRACE("video_frame coded_n:%d", frame->coded_picture_number);
/* copy decoded frame to destination buffer:
* this is required since rawvideo expects non aligned data
*/
av_image_copy(ffmpeg_ctx->video_src_data, ffmpeg_ctx->video_src_linesize,
(const uint8_t **)(frame->data), frame->linesize,
ffmpeg_ctx->video_dec_ctx->pix_fmt, width, height);
if(ffmpeg_ctx->sws_ctx == NULL) {
int swsFlags = SWS_BILINEAR;
if(ffmpeg_pix_fmt_is_yuv(ffmpeg_ctx->video_dec_ctx->pix_fmt)) {
/* When the video width and height are not multiples of 8,
* and there is no size change in the conversion,
* a blurry screen will appear on the right side
* This problem was discovered in 2012 and
* continues to exist in version 4.1.3 in 2019
* This problem can be avoided by increasing SWS_ACCURATE_RND
*/
if((width & 0x7) || (height & 0x7)) {
LV_LOG_WARN("The width(%d) and height(%d) the image "
"is not a multiple of 8, "
"the decoding speed may be reduced",
width, height);
swsFlags |= SWS_ACCURATE_RND;
}
}
ffmpeg_ctx->sws_ctx = sws_getContext(
width, height, ffmpeg_ctx->video_dec_ctx->pix_fmt,
width, height, ffmpeg_ctx->video_dst_pix_fmt,
swsFlags,
NULL, NULL, NULL);
}
if(!ffmpeg_ctx->has_alpha) {
int lv_linesize = lv_color_format_get_size(LV_COLOR_FORMAT_NATIVE) * width;
int dst_linesize = ffmpeg_ctx->video_dst_linesize[0];
if(dst_linesize != lv_linesize) {
LV_LOG_WARN("ffmpeg linesize = %d, but lvgl image require %d",
dst_linesize,
lv_linesize);
ffmpeg_ctx->video_dst_linesize[0] = lv_linesize;
}
}
ret = sws_scale(
ffmpeg_ctx->sws_ctx,
(const uint8_t * const *)(ffmpeg_ctx->video_src_data),
ffmpeg_ctx->video_src_linesize,
0,
height,
ffmpeg_ctx->video_dst_data,
ffmpeg_ctx->video_dst_linesize);
failed:
return ret;
}
static int ffmpeg_decode_packet(AVCodecContext * dec, const AVPacket * pkt,
struct ffmpeg_context_s * ffmpeg_ctx)
{
int ret = 0;
/* submit the packet to the decoder */
ret = avcodec_send_packet(dec, pkt);
if(ret < 0) {
LV_LOG_ERROR("Error submitting a packet for decoding (%s)",
av_err2str(ret));
return ret;
}
/* get all the available frames from the decoder */
while(ret >= 0) {
ret = avcodec_receive_frame(dec, ffmpeg_ctx->frame);
if(ret < 0) {
/* those two return values are special and mean there is
* no output frame available,
* but there were no errors during decoding
*/
if(ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) {
return 0;
}
LV_LOG_ERROR("Error during decoding (%s)", av_err2str(ret));
return ret;
}
/* write the frame data to output file */
if(dec->codec->type == AVMEDIA_TYPE_VIDEO) {
ret = ffmpeg_output_video_frame(ffmpeg_ctx);
}
av_frame_unref(ffmpeg_ctx->frame);
if(ret < 0) {
LV_LOG_WARN("ffmpeg_decode_packet ended %d", ret);
return ret;
}
}
return 0;
}
static int ffmpeg_open_codec_context(int * stream_idx,
AVCodecContext ** dec_ctx, AVFormatContext * fmt_ctx,
enum AVMediaType type)
{
int ret;
int stream_index;
AVStream * st;
const AVCodec * dec = NULL;
AVDictionary * opts = NULL;
ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
if(ret < 0) {
LV_LOG_ERROR("Could not find %s stream in input file",
av_get_media_type_string(type));
return ret;
}
else {
stream_index = ret;
st = fmt_ctx->streams[stream_index];
/* find decoder for the stream */
dec = avcodec_find_decoder(st->codecpar->codec_id);
if(dec == NULL) {
LV_LOG_ERROR("Failed to find %s codec",
av_get_media_type_string(type));
return AVERROR(EINVAL);
}
/* Allocate a codec context for the decoder */
*dec_ctx = avcodec_alloc_context3(dec);
if(*dec_ctx == NULL) {
LV_LOG_ERROR("Failed to allocate the %s codec context",
av_get_media_type_string(type));
return AVERROR(ENOMEM);
}
/* Copy codec parameters from input stream to output codec context */
if((ret = avcodec_parameters_to_context(*dec_ctx, st->codecpar)) < 0) {
LV_LOG_ERROR(
"Failed to copy %s codec parameters to decoder context",
av_get_media_type_string(type));
return ret;
}
/* Init the decoders */
if((ret = avcodec_open2(*dec_ctx, dec, &opts)) < 0) {
LV_LOG_ERROR("Failed to open %s codec",
av_get_media_type_string(type));
return ret;
}
*stream_idx = stream_index;
}
return 0;
}
static int ffmpeg_get_image_header(const char * filepath,
lv_image_header_t * header)
{
int ret = -1;
AVFormatContext * fmt_ctx = NULL;
AVCodecContext * video_dec_ctx = NULL;
int video_stream_idx;
/* open input file, and allocate format context */
if(avformat_open_input(&fmt_ctx, filepath, NULL, NULL) < 0) {
LV_LOG_ERROR("Could not open source file %s", filepath);
goto failed;
}
/* retrieve stream information */
if(avformat_find_stream_info(fmt_ctx, NULL) < 0) {
LV_LOG_ERROR("Could not find stream information");
goto failed;
}
if(ffmpeg_open_codec_context(&video_stream_idx, &video_dec_ctx,
fmt_ctx, AVMEDIA_TYPE_VIDEO)
>= 0) {
bool has_alpha = ffmpeg_pix_fmt_has_alpha(video_dec_ctx->pix_fmt);
/* allocate image where the decoded image will be put */
header->w = video_dec_ctx->width;
header->h = video_dec_ctx->height;
header->always_zero = 0;
header->cf = has_alpha ? LV_COLOR_FORMAT_ARGB8888 : LV_COLOR_FORMAT_NATIVE;
ret = 0;
}
failed:
avcodec_free_context(&video_dec_ctx);
avformat_close_input(&fmt_ctx);
return ret;
}
static int ffmpeg_get_frame_refr_period(struct ffmpeg_context_s * ffmpeg_ctx)
{
int avg_frame_rate_num = ffmpeg_ctx->video_stream->avg_frame_rate.num;
if(avg_frame_rate_num > 0) {
int period = 1000 * (int64_t)ffmpeg_ctx->video_stream->avg_frame_rate.den
/ avg_frame_rate_num;
return period;
}
return -1;
}
static int ffmpeg_update_next_frame(struct ffmpeg_context_s * ffmpeg_ctx)
{
int ret = 0;
while(1) {
/* read frames from the file */
if(av_read_frame(ffmpeg_ctx->fmt_ctx, ffmpeg_ctx->pkt) >= 0) {
bool is_image = false;
/* check if the packet belongs to a stream we are interested in,
* otherwise skip it
*/
if(ffmpeg_ctx->pkt->stream_index == ffmpeg_ctx->video_stream_idx) {
ret = ffmpeg_decode_packet(ffmpeg_ctx->video_dec_ctx,
ffmpeg_ctx->pkt, ffmpeg_ctx);
is_image = true;
}
av_packet_unref(ffmpeg_ctx->pkt);
if(ret < 0) {
LV_LOG_WARN("video frame is empty %d", ret);
break;
}
/* Used to filter data that is not an image */
if(is_image) {
break;
}
}
else {
ret = -1;
break;
}
}
return ret;
}
struct ffmpeg_context_s * ffmpeg_open_file(const char * path)
{
if(path == NULL || lv_strlen(path) == 0) {
LV_LOG_ERROR("file path is empty");
return NULL;
}
struct ffmpeg_context_s * ffmpeg_ctx = calloc(1, sizeof(struct ffmpeg_context_s));
if(ffmpeg_ctx == NULL) {
LV_LOG_ERROR("ffmpeg_ctx malloc failed");
goto failed;
}
/* open input file, and allocate format context */
if(avformat_open_input(&(ffmpeg_ctx->fmt_ctx), path, NULL, NULL) < 0) {
LV_LOG_ERROR("Could not open source file %s", path);
goto failed;
}
/* retrieve stream information */
if(avformat_find_stream_info(ffmpeg_ctx->fmt_ctx, NULL) < 0) {
LV_LOG_ERROR("Could not find stream information");
goto failed;
}
if(ffmpeg_open_codec_context(
&(ffmpeg_ctx->video_stream_idx),
&(ffmpeg_ctx->video_dec_ctx),
ffmpeg_ctx->fmt_ctx, AVMEDIA_TYPE_VIDEO)
>= 0) {
ffmpeg_ctx->video_stream = ffmpeg_ctx->fmt_ctx->streams[ffmpeg_ctx->video_stream_idx];
ffmpeg_ctx->has_alpha = ffmpeg_pix_fmt_has_alpha(ffmpeg_ctx->video_dec_ctx->pix_fmt);
ffmpeg_ctx->video_dst_pix_fmt = (ffmpeg_ctx->has_alpha ? AV_PIX_FMT_BGRA : AV_PIX_FMT_TRUE_COLOR);
}
#if LV_FFMPEG_AV_DUMP_FORMAT != 0
/* dump input information to stderr */
av_dump_format(ffmpeg_ctx->fmt_ctx, 0, path, 0);
#endif
if(ffmpeg_ctx->video_stream == NULL) {
LV_LOG_ERROR("Could not find video stream in the input, aborting");
goto failed;
}
return ffmpeg_ctx;
failed:
ffmpeg_close(ffmpeg_ctx);
return NULL;
}
static int ffmpeg_image_allocate(struct ffmpeg_context_s * ffmpeg_ctx)
{
int ret;
/* allocate image where the decoded image will be put */
ret = av_image_alloc(
ffmpeg_ctx->video_src_data,
ffmpeg_ctx->video_src_linesize,
ffmpeg_ctx->video_dec_ctx->width,
ffmpeg_ctx->video_dec_ctx->height,
ffmpeg_ctx->video_dec_ctx->pix_fmt,
4);
if(ret < 0) {
LV_LOG_ERROR("Could not allocate src raw video buffer");
return ret;
}
LV_LOG_INFO("alloc video_src_bufsize = %d", ret);
ret = av_image_alloc(
ffmpeg_ctx->video_dst_data,
ffmpeg_ctx->video_dst_linesize,
ffmpeg_ctx->video_dec_ctx->width,
ffmpeg_ctx->video_dec_ctx->height,
ffmpeg_ctx->video_dst_pix_fmt,
4);
if(ret < 0) {
LV_LOG_ERROR("Could not allocate dst raw video buffer");
return ret;
}
LV_LOG_INFO("allocate video_dst_bufsize = %d", ret);
ffmpeg_ctx->frame = av_frame_alloc();
if(ffmpeg_ctx->frame == NULL) {
LV_LOG_ERROR("Could not allocate frame");
return -1;
}
/* allocate packet, set data to NULL, let the demuxer fill it */
ffmpeg_ctx->pkt = av_packet_alloc();
if(ffmpeg_ctx->pkt == NULL) {
LV_LOG_ERROR("av_packet_alloc failed");
return -1;
}
ffmpeg_ctx->pkt->data = NULL;
ffmpeg_ctx->pkt->size = 0;
return 0;
}
static void ffmpeg_close_src_ctx(struct ffmpeg_context_s * ffmpeg_ctx)
{
avcodec_free_context(&(ffmpeg_ctx->video_dec_ctx));
avformat_close_input(&(ffmpeg_ctx->fmt_ctx));
av_frame_free(&(ffmpeg_ctx->frame));
if(ffmpeg_ctx->video_src_data[0] != NULL) {
av_free(ffmpeg_ctx->video_src_data[0]);
ffmpeg_ctx->video_src_data[0] = NULL;
}
}
static void ffmpeg_close_dst_ctx(struct ffmpeg_context_s * ffmpeg_ctx)
{
if(ffmpeg_ctx->video_dst_data[0] != NULL) {
av_free(ffmpeg_ctx->video_dst_data[0]);
ffmpeg_ctx->video_dst_data[0] = NULL;
}
}
static void ffmpeg_close(struct ffmpeg_context_s * ffmpeg_ctx)
{
if(ffmpeg_ctx == NULL) {
LV_LOG_WARN("ffmpeg_ctx is NULL");
return;
}
sws_freeContext(ffmpeg_ctx->sws_ctx);
ffmpeg_close_src_ctx(ffmpeg_ctx);
ffmpeg_close_dst_ctx(ffmpeg_ctx);
free(ffmpeg_ctx);
LV_LOG_INFO("ffmpeg_ctx closed");
}
static void lv_ffmpeg_player_frame_update_cb(lv_timer_t * timer)
{
lv_obj_t * obj = (lv_obj_t *)timer->user_data;
lv_ffmpeg_player_t * player = (lv_ffmpeg_player_t *)obj;
if(!player->ffmpeg_ctx) {
return;
}
int has_next = ffmpeg_update_next_frame(player->ffmpeg_ctx);
if(has_next < 0) {
lv_ffmpeg_player_set_cmd(obj, player->auto_restart ? LV_FFMPEG_PLAYER_CMD_START : LV_FFMPEG_PLAYER_CMD_STOP);
return;
}
lv_cache_lock();
lv_cache_invalidate(lv_cache_find(lv_image_get_src(obj), LV_CACHE_SRC_TYPE_PTR, 0, 0));
lv_cache_unlock();
lv_obj_invalidate(obj);
}
static void lv_ffmpeg_player_constructor(const lv_obj_class_t * class_p,
lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_ffmpeg_player_t * player = (lv_ffmpeg_player_t *)obj;
player->auto_restart = false;
player->ffmpeg_ctx = NULL;
player->timer = lv_timer_create(lv_ffmpeg_player_frame_update_cb,
FRAME_DEF_REFR_PERIOD, obj);
lv_timer_pause(player->timer);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_ffmpeg_player_destructor(const lv_obj_class_t * class_p,
lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_ffmpeg_player_t * player = (lv_ffmpeg_player_t *)obj;
if(player->timer) {
lv_timer_delete(player->timer);
player->timer = NULL;
}
lv_cache_lock();
lv_cache_invalidate(lv_cache_find(lv_image_get_src(obj), LV_CACHE_SRC_TYPE_PTR, 0, 0));
lv_cache_unlock();
ffmpeg_close(player->ffmpeg_ctx);
player->ffmpeg_ctx = NULL;
LV_TRACE_OBJ_CREATE("finished");
}
#endif /*LV_USE_FFMPEG*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/libjpeg_turbo/lv_libjpeg_turbo.h | /**
* @file lv_libjpeg_turbo.h
*
*/
#ifndef LV_LIBJPEG_TURBO_H
#define LV_LIBJPEG_TURBO_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../lv_conf_internal.h"
#if LV_USE_LIBJPEG_TURBO
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Register the JPEG-Turbo decoder functions in LVGL
*/
void lv_libjpeg_turbo_init(void);
void lv_libjpeg_turbo_deinit(void);
/**********************
* MACROS
**********************/
#endif /*LV_USE_LIBJPEG_TURBO*/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*LV_LIBJPEG_TURBO_H*/ |
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs | repos/zig_workbench/BaseLVGL/lib/lvgl/src/libs/libjpeg_turbo/lv_libjpeg_turbo.c | /**
* @file lv_libjpeg_turbo.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_LIBJPEG_TURBO
#include "lv_libjpeg_turbo.h"
#include <stdio.h>
#include <jpeglib.h>
#include <setjmp.h>
/*********************
* DEFINES
*********************/
#define JPEG_PIXEL_SIZE 3 /* RGB888 */
#define JPEG_SIGNATURE 0xFFD8FF
#define IS_JPEG_SIGNATURE(x) (((x) & 0x00FFFFFF) == JPEG_SIGNATURE)
/**********************
* TYPEDEFS
**********************/
typedef struct error_mgr_s {
struct jpeg_error_mgr pub;
jmp_buf jb;
} error_mgr_t;
/**********************
* STATIC PROTOTYPES
**********************/
static lv_result_t decoder_info(lv_image_decoder_t * decoder, const void * src, lv_image_header_t * header);
static lv_result_t decoder_open(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc);
static void decoder_close(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc);
static const void * decode_jpeg_file(const char * filename);
static bool get_jpeg_size(const char * filename, uint32_t * width, uint32_t * height);
static void error_exit(j_common_ptr cinfo);
static lv_result_t try_cache(lv_image_decoder_dsc_t * dsc);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Register the JPEG decoder functions in LVGL
*/
void lv_libjpeg_turbo_init(void)
{
lv_image_decoder_t * dec = lv_image_decoder_create();
lv_image_decoder_set_info_cb(dec, decoder_info);
lv_image_decoder_set_open_cb(dec, decoder_open);
lv_image_decoder_set_close_cb(dec, decoder_close);
}
void lv_libjpeg_turbo_deinit(void)
{
lv_image_decoder_t * dec = NULL;
while((dec = lv_image_decoder_get_next(dec)) != NULL) {
if(dec->info_cb == decoder_info) {
lv_image_decoder_delete(dec);
break;
}
}
}
/**********************
* STATIC FUNCTIONS
**********************/
/**
* Get info about a JPEG image
* @param src can be file name or pointer to a C array
* @param header store the info here
* @return LV_RESULT_OK: no error; LV_RESULT_INVALID: can't get the info
*/
static lv_result_t decoder_info(lv_image_decoder_t * decoder, const void * src, lv_image_header_t * header)
{
LV_UNUSED(decoder); /*Unused*/
lv_image_src_t src_type = lv_image_src_get_type(src); /*Get the source type*/
/*If it's a JPEG file...*/
if(src_type == LV_IMAGE_SRC_FILE) {
const char * fn = src;
lv_fs_file_t f;
lv_fs_res_t res = lv_fs_open(&f, fn, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) {
LV_LOG_WARN("Can't open file: %s", fn);
return LV_RESULT_INVALID;
}
uint32_t jpg_signature = 0;
uint32_t rn;
lv_fs_read(&f, &jpg_signature, sizeof(jpg_signature), &rn);
lv_fs_close(&f);
if(rn != sizeof(jpg_signature)) {
LV_LOG_WARN("file: %s signature len = %" LV_PRIu32 " error", fn, rn);
return LV_RESULT_INVALID;
}
bool is_jpeg_ext = (strcmp(lv_fs_get_ext(fn), "jpg") == 0)
|| (strcmp(lv_fs_get_ext(fn), "jpeg") == 0);
if(!IS_JPEG_SIGNATURE(jpg_signature)) {
if(is_jpeg_ext) {
LV_LOG_WARN("file: %s signature = 0X%" LV_PRIX32 " error", fn, jpg_signature);
}
return LV_RESULT_INVALID;
}
uint32_t width;
uint32_t height;
if(!get_jpeg_size(fn, &width, &height)) {
return LV_RESULT_INVALID;
}
/*Save the data in the header*/
header->always_zero = 0;
header->cf = LV_COLOR_FORMAT_RGB888;
header->w = width;
header->h = height;
return LV_RESULT_OK;
}
return LV_RESULT_INVALID; /*If didn't succeeded earlier then it's an error*/
}
/**
* Open a JPEG image and return the decided image
* @param src can be file name or pointer to a C array
* @param style style of the image object (unused now but certain formats might use it)
* @return pointer to the decoded image or `LV_IMAGE_DECODER_OPEN_FAIL` if failed
*/
static lv_result_t decoder_open(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder); /*Unused*/
/*Check the cache first*/
if(try_cache(dsc) == LV_RESULT_OK) return LV_RESULT_OK;
/*If it's a JPEG file...*/
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
const char * fn = dsc->src;
lv_cache_lock();
lv_cache_entry_t * cache = lv_cache_add(dsc->header.w * dsc->header.h * JPEG_PIXEL_SIZE);
if(cache == NULL) {
lv_cache_unlock();
return LV_RESULT_INVALID;
}
uint32_t t = lv_tick_get();
const void * decoded_img = decode_jpeg_file(fn);
t = lv_tick_elaps(t);
cache->weight = t;
cache->data = decoded_img;
cache->free_data = 1;
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
cache->src = lv_strdup(dsc->src);
cache->src_type = LV_CACHE_SRC_TYPE_STR;
cache->free_src = 1;
}
else {
cache->src_type = LV_CACHE_SRC_TYPE_PTR;
cache->src = dsc->src;
}
dsc->img_data = lv_cache_get_data(cache);
dsc->cache_entry = cache;
lv_cache_unlock();
return LV_RESULT_OK; /*If not returned earlier then it failed*/
}
return LV_RESULT_INVALID; /*If not returned earlier then it failed*/
}
/**
* Free the allocated resources
*/
static void decoder_close(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder); /*Unused*/
lv_cache_lock();
lv_cache_release(dsc->cache_entry);
lv_cache_unlock();
}
static lv_result_t try_cache(lv_image_decoder_dsc_t * dsc)
{
lv_cache_lock();
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
const char * fn = dsc->src;
lv_cache_entry_t * cache = lv_cache_find(fn, LV_CACHE_SRC_TYPE_STR, 0, 0);
if(cache) {
dsc->img_data = lv_cache_get_data(cache);
dsc->cache_entry = cache; /*Save the cache to release it in decoder_close*/
lv_cache_unlock();
return LV_RESULT_OK;
}
}
lv_cache_unlock();
return LV_RESULT_INVALID;
}
static uint8_t * alloc_file(const char * filename, uint32_t * size)
{
uint8_t * data = NULL;
lv_fs_file_t f;
uint32_t data_size;
uint32_t rn;
lv_fs_res_t res;
*size = 0;
res = lv_fs_open(&f, filename, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) {
LV_LOG_WARN("can't open %s", filename);
return NULL;
}
res = lv_fs_seek(&f, 0, LV_FS_SEEK_END);
if(res != LV_FS_RES_OK) {
goto failed;
}
res = lv_fs_tell(&f, &data_size);
if(res != LV_FS_RES_OK) {
goto failed;
}
res = lv_fs_seek(&f, 0, LV_FS_SEEK_SET);
if(res != LV_FS_RES_OK) {
goto failed;
}
/*Read file to buffer*/
data = lv_malloc(data_size);
if(data == NULL) {
LV_LOG_WARN("malloc failed for data");
goto failed;
}
res = lv_fs_read(&f, data, data_size, &rn);
if(res == LV_FS_RES_OK && rn == data_size) {
*size = rn;
}
else {
LV_LOG_WARN("read file failed");
lv_free(data);
data = NULL;
}
failed:
lv_fs_close(&f);
return data;
}
static const void * decode_jpeg_file(const char * filename)
{
/* This struct contains the JPEG decompression parameters and pointers to
* working space (which is allocated as needed by the JPEG library).
*/
struct jpeg_decompress_struct cinfo;
/* We use our private extension JPEG error handler.
* Note that this struct must live as long as the main JPEG parameter
* struct, to avoid dangling-pointer problems.
*/
error_mgr_t jerr;
/* More stuff */
JSAMPARRAY buffer; /* Output row buffer */
int row_stride; /* physical row width in output buffer */
uint8_t * output_buffer = NULL;
/* In this example we want to open the input file before doing anything else,
* so that the setjmp() error recovery below can assume the file is open.
* VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
* requires it in order to read binary files.
*/
uint32_t data_size;
uint8_t * data = alloc_file(filename, &data_size);
if(data == NULL) {
LV_LOG_WARN("can't load file %s", filename);
return NULL;
}
/* allocate and initialize JPEG decompression object */
/* We set up the normal JPEG error routines, then override error_exit. */
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = error_exit;
/* Establish the setjmp return context for my_error_exit to use. */
if(setjmp(jerr.jb)) {
LV_LOG_WARN("decoding error");
if(output_buffer) {
lv_draw_buf_free(output_buffer);
}
/* If we get here, the JPEG code has signaled an error.
* We need to clean up the JPEG object, close the input file, and return.
*/
jpeg_destroy_decompress(&cinfo);
lv_free(data);
return NULL;
}
/* Now we can initialize the JPEG decompression object. */
jpeg_create_decompress(&cinfo);
/* specify data source (eg, a file or buffer) */
jpeg_mem_src(&cinfo, data, data_size);
/* read file parameters with jpeg_read_header() */
jpeg_read_header(&cinfo, TRUE);
/* We can ignore the return value from jpeg_read_header since
* (a) suspension is not possible with the stdio data source, and
* (b) we passed TRUE to reject a tables-only JPEG file as an error.
* See libjpeg.doc for more info.
*/
/* set parameters for decompression */
cinfo.out_color_space = JCS_EXT_BGR;
/* In this example, we don't need to change any of the defaults set by
* jpeg_read_header(), so we do nothing here.
*/
/* Start decompressor */
jpeg_start_decompress(&cinfo);
/* We can ignore the return value since suspension is not possible
* with the stdio data source.
*/
/* We may need to do some setup of our own at this point before reading
* the data. After jpeg_start_decompress() we have the correct scaled
* output image dimensions available, as well as the output colormap
* if we asked for color quantization.
* In this example, we need to make an output work buffer of the right size.
*/
/* JSAMPLEs per row in output buffer */
row_stride = cinfo.output_width * cinfo.output_components;
/* Make a one-row-high sample array that will go away when done with image */
buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
size_t output_buffer_size = cinfo.output_width * cinfo.output_height * JPEG_PIXEL_SIZE;
output_buffer = lv_draw_buf_malloc(output_buffer_size, LV_COLOR_FORMAT_RGB888);
if(output_buffer) {
uint8_t * cur_pos = output_buffer;
size_t stride = cinfo.output_width * JPEG_PIXEL_SIZE;
/* while (scan lines remain to be read) */
/* jpeg_read_scanlines(...); */
/* Here we use the library's state variable cinfo.output_scanline as the
* loop counter, so that we don't have to keep track ourselves.
*/
while(cinfo.output_scanline < cinfo.output_height) {
/* jpeg_read_scanlines expects an array of pointers to scanlines.
* Here the array is only one element long, but you could ask for
* more than one scanline at a time if that's more convenient.
*/
jpeg_read_scanlines(&cinfo, buffer, 1);
/* Assume put_scanline_someplace wants a pointer and sample count. */
lv_memcpy(cur_pos, buffer[0], stride);
cur_pos += stride;
}
}
/* Finish decompression */
jpeg_finish_decompress(&cinfo);
/* We can ignore the return value since suspension is not possible
* with the stdio data source.
*/
/* Release JPEG decompression object */
/* This is an important step since it will release a good deal of memory. */
jpeg_destroy_decompress(&cinfo);
/* After finish_decompress, we can close the input file.
* Here we postpone it until after no more JPEG errors are possible,
* so as to simplify the setjmp error logic above. (Actually, I don't
* think that jpeg_destroy can do an error exit, but why assume anything...)
*/
lv_free(data);
/* At this point you may want to check to see whether any corrupt-data
* warnings occurred (test whether jerr.pub.num_warnings is nonzero).
*/
/* And we're done! */
return output_buffer;
}
static bool get_jpeg_size(const char * filename, uint32_t * width, uint32_t * height)
{
struct jpeg_decompress_struct cinfo;
error_mgr_t jerr;
uint8_t * data = NULL;
uint32_t data_size;
data = alloc_file(filename, &data_size);
if(data == NULL) {
return false;
}
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = error_exit;
if(setjmp(jerr.jb)) {
LV_LOG_WARN("read jpeg head failed");
jpeg_destroy_decompress(&cinfo);
lv_free(data);
return false;
}
jpeg_create_decompress(&cinfo);
jpeg_mem_src(&cinfo, data, data_size);
int ret = jpeg_read_header(&cinfo, TRUE);
if(ret == JPEG_HEADER_OK) {
*width = cinfo.image_width;
*height = cinfo.image_height;
}
else {
LV_LOG_WARN("read jpeg head failed: %d", ret);
}
jpeg_destroy_decompress(&cinfo);
lv_free(data);
return (ret == JPEG_HEADER_OK);
}
static void error_exit(j_common_ptr cinfo)
{
error_mgr_t * myerr = (error_mgr_t *)cinfo->err;
(*cinfo->err->output_message)(cinfo);
longjmp(myerr->jb, 1);
}
#endif /*LV_USE_LIBJPEG_TURBO*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/indev/lv_indev.c | /**
* @file lv_indev.c
*
*/
/*********************
* INCLUDES
********************/
#include "lv_indev_private.h"
#include "lv_indev_scroll.h"
#include "../display/lv_display_private.h"
#include "../core/lv_global.h"
#include "../core/lv_obj.h"
#include "../core/lv_group.h"
#include "../core/lv_refr.h"
#include "../tick/lv_tick.h"
#include "../misc/lv_timer.h"
#include "../misc/lv_math.h"
#include "../misc/lv_profiler.h"
#include "../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
/*Drag threshold in pixels*/
#define LV_INDEV_DEF_SCROLL_LIMIT 10
/*Drag throw slow-down in [%]. Greater value -> faster slow-down*/
#define LV_INDEV_DEF_SCROLL_THROW 10
/*Long press time in milliseconds.
*Time to send `LV_EVENT_LONG_PRESSSED`)*/
#define LV_INDEV_DEF_LONG_PRESS_TIME 400
/*Repeated trigger period in long press [ms]
*Time between `LV_EVENT_LONG_PRESSED_REPEAT*/
#define LV_INDEV_DEF_LONG_PRESS_REP_TIME 100
/*Gesture threshold in pixels*/
#define LV_INDEV_DEF_GESTURE_LIMIT 50
/*Gesture min velocity at release before swipe (pixels)*/
#define LV_INDEV_DEF_GESTURE_MIN_VELOCITY 3
#if LV_INDEV_DEF_SCROLL_THROW <= 0
#warning "LV_INDEV_DRAG_THROW must be greater than 0"
#endif
#define indev_act LV_GLOBAL_DEFAULT()->indev_active
#define indev_obj_act LV_GLOBAL_DEFAULT()->indev_obj_active
#define indev_ll_head &(LV_GLOBAL_DEFAULT()->indev_ll)
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void indev_pointer_proc(lv_indev_t * i, lv_indev_data_t * data);
static void indev_keypad_proc(lv_indev_t * i, lv_indev_data_t * data);
static void indev_encoder_proc(lv_indev_t * i, lv_indev_data_t * data);
static void indev_button_proc(lv_indev_t * i, lv_indev_data_t * data);
static void indev_proc_press(lv_indev_t * indev);
static void indev_proc_release(lv_indev_t * indev);
static lv_obj_t * pointer_search_obj(lv_display_t * disp, lv_point_t * p);
static void indev_proc_reset_query_handler(lv_indev_t * indev);
static void indev_click_focus(lv_indev_t * indev);
static void indev_gesture(lv_indev_t * indev);
static bool indev_reset_check(lv_indev_t * indev);
static void indev_read_core(lv_indev_t * indev, lv_indev_data_t * data);
static void indev_reset_core(lv_indev_t * indev, lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
#if LV_USE_LOG && LV_LOG_TRACE_INDEV
#define LV_TRACE_INDEV(...) LV_LOG_TRACE(__VA_ARGS__)
#else
#define LV_TRACE_INDEV(...)
#endif
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_indev_t * lv_indev_create(void)
{
lv_display_t * disp = lv_display_get_default();
if(disp == NULL) {
LV_LOG_WARN("no display was created so far");
}
lv_indev_t * indev = _lv_ll_ins_head(indev_ll_head);
LV_ASSERT_MALLOC(indev);
if(!indev) {
return NULL;
}
lv_memzero(indev, sizeof(lv_indev_t));
indev->reset_query = 1;
indev->read_timer = lv_timer_create(lv_indev_read_timer_cb, LV_DEF_REFR_PERIOD, indev);
indev->disp = lv_display_get_default();
indev->type = LV_INDEV_TYPE_NONE;
indev->scroll_limit = LV_INDEV_DEF_SCROLL_LIMIT;
indev->scroll_throw = LV_INDEV_DEF_SCROLL_THROW;
indev->long_press_time = LV_INDEV_DEF_LONG_PRESS_TIME;
indev->long_press_repeat_time = LV_INDEV_DEF_LONG_PRESS_REP_TIME;
indev->gesture_limit = LV_INDEV_DEF_GESTURE_LIMIT;
indev->gesture_min_velocity = LV_INDEV_DEF_GESTURE_MIN_VELOCITY;
return indev;
}
void lv_indev_delete(lv_indev_t * indev)
{
LV_ASSERT_NULL(indev);
/*Clean up the read timer first*/
if(indev->read_timer) lv_timer_delete(indev->read_timer);
/*Remove the input device from the list*/
_lv_ll_remove(indev_ll_head, indev);
/*Free the memory of the input device*/
lv_free(indev);
}
lv_indev_t * lv_indev_get_next(lv_indev_t * indev)
{
if(indev == NULL)
return _lv_ll_get_head(indev_ll_head);
else
return _lv_ll_get_next(indev_ll_head, indev);
}
void indev_read_core(lv_indev_t * indev, lv_indev_data_t * data)
{
LV_PROFILER_BEGIN;
lv_memzero(data, sizeof(lv_indev_data_t));
/* For touchpad sometimes users don't set the last pressed coordinate on release.
* So be sure a coordinates are initialized to the last point */
if(indev->type == LV_INDEV_TYPE_POINTER) {
data->point.x = indev->pointer.last_raw_point.x;
data->point.y = indev->pointer.last_raw_point.y;
}
/*Similarly set at least the last key in case of the user doesn't set it on release*/
else if(indev->type == LV_INDEV_TYPE_KEYPAD) {
data->key = indev->keypad.last_key;
}
/*For compatibility assume that used button was enter (encoder push)*/
else if(indev->type == LV_INDEV_TYPE_ENCODER) {
data->key = LV_KEY_ENTER;
}
if(indev->read_cb) {
LV_TRACE_INDEV("calling indev_read_cb");
indev->read_cb(indev, data);
}
else {
LV_LOG_WARN("indev_read_cb is not registered");
}
LV_PROFILER_END;
}
void lv_indev_read_timer_cb(lv_timer_t * timer)
{
lv_indev_read(timer->user_data);
}
void lv_indev_read(lv_indev_t * indev_p)
{
if(!indev_p) return;
LV_TRACE_INDEV("begin");
indev_act = indev_p;
/*Read and process all indevs*/
if(indev_p->disp == NULL) return; /*Not assigned to any displays*/
/*Handle reset query before processing the point*/
indev_proc_reset_query_handler(indev_p);
if(indev_p->disabled ||
indev_p->disp->prev_scr != NULL) return; /*Input disabled or screen animation active*/
LV_PROFILER_BEGIN;
bool continue_reading;
lv_indev_data_t data;
do {
/*Read the data*/
indev_read_core(indev_p, &data);
continue_reading = data.continue_reading;
/*The active object might be deleted even in the read function*/
indev_proc_reset_query_handler(indev_p);
indev_obj_act = NULL;
indev_p->state = data.state;
/*Save the last activity time*/
if(indev_p->state == LV_INDEV_STATE_PRESSED) {
indev_p->disp->last_activity_time = lv_tick_get();
}
else if(indev_p->type == LV_INDEV_TYPE_ENCODER && data.enc_diff) {
indev_p->disp->last_activity_time = lv_tick_get();
}
if(indev_p->type == LV_INDEV_TYPE_POINTER) {
indev_pointer_proc(indev_p, &data);
}
else if(indev_p->type == LV_INDEV_TYPE_KEYPAD) {
indev_keypad_proc(indev_p, &data);
}
else if(indev_p->type == LV_INDEV_TYPE_ENCODER) {
indev_encoder_proc(indev_p, &data);
}
else if(indev_p->type == LV_INDEV_TYPE_BUTTON) {
indev_button_proc(indev_p, &data);
}
/*Handle reset query if it happened in during processing*/
indev_proc_reset_query_handler(indev_p);
} while(continue_reading);
/*End of indev processing, so no act indev*/
indev_act = NULL;
indev_obj_act = NULL;
LV_TRACE_INDEV("finished");
LV_PROFILER_END;
}
void lv_indev_enable(lv_indev_t * indev, bool en)
{
uint8_t enable = en ? 0 : 1;
if(indev) {
indev->disabled = enable;
}
else {
lv_indev_t * i = lv_indev_get_next(NULL);
while(i) {
i->disabled = enable;
i = lv_indev_get_next(i);
}
}
}
lv_indev_t * lv_indev_active(void)
{
return indev_act;
}
void lv_indev_set_type(lv_indev_t * indev, lv_indev_type_t indev_type)
{
if(indev == NULL) return;
indev->type = indev_type;
indev->reset_query = 1;
}
void lv_indev_set_read_cb(lv_indev_t * indev, lv_indev_read_cb_t read_cb)
{
if(indev == NULL) return;
indev->read_cb = read_cb;
}
void lv_indev_set_user_data(lv_indev_t * indev, void * user_data)
{
if(indev == NULL) return;
indev->user_data = user_data;
}
void lv_indev_set_driver_data(lv_indev_t * indev, void * driver_data)
{
if(indev == NULL) return;
indev->driver_data = driver_data;
}
lv_indev_type_t lv_indev_get_type(const lv_indev_t * indev)
{
if(indev == NULL) return LV_INDEV_TYPE_NONE;
return indev->type;
}
lv_indev_state_t lv_indev_get_state(const lv_indev_t * indev)
{
if(indev == NULL) return LV_INDEV_STATE_RELEASED;
return indev->state;
}
lv_group_t * lv_indev_get_group(const lv_indev_t * indev)
{
if(indev == NULL) return NULL;
return indev->group;
}
lv_display_t * lv_indev_get_disp(const lv_indev_t * indev)
{
if(indev == NULL) return NULL;
return indev->disp;
}
void lv_indev_set_disp(lv_indev_t * indev, lv_display_t * disp)
{
if(indev == NULL) return;
indev->disp = disp;
}
void * lv_indev_get_user_data(const lv_indev_t * indev)
{
if(indev == NULL) return NULL;
return indev->user_data;
}
void * lv_indev_get_driver_data(const lv_indev_t * indev)
{
if(indev == NULL) return NULL;
return indev->driver_data;
}
void lv_indev_reset(lv_indev_t * indev, lv_obj_t * obj)
{
if(indev) {
indev_reset_core(indev, obj);
}
else {
lv_indev_t * i = lv_indev_get_next(NULL);
while(i) {
indev_reset_core(i, obj);
i = lv_indev_get_next(i);
}
indev_obj_act = NULL;
}
}
void lv_indev_reset_long_press(lv_indev_t * indev)
{
indev->long_pr_sent = 0;
indev->longpr_rep_timestamp = lv_tick_get();
indev->pr_timestamp = lv_tick_get();
}
void lv_indev_set_cursor(lv_indev_t * indev, lv_obj_t * cur_obj)
{
if(indev->type != LV_INDEV_TYPE_POINTER) return;
indev->cursor = cur_obj;
lv_obj_set_parent(indev->cursor, lv_display_get_layer_sys(indev->disp));
lv_obj_set_pos(indev->cursor, indev->pointer.act_point.x, indev->pointer.act_point.y);
lv_obj_remove_flag(indev->cursor, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_flag(indev->cursor, LV_OBJ_FLAG_IGNORE_LAYOUT | LV_OBJ_FLAG_FLOATING);
}
void lv_indev_set_group(lv_indev_t * indev, lv_group_t * group)
{
if(indev->type == LV_INDEV_TYPE_KEYPAD || indev->type == LV_INDEV_TYPE_ENCODER) {
indev->group = group;
}
}
void lv_indev_set_button_points(lv_indev_t * indev, const lv_point_t points[])
{
if(indev->type == LV_INDEV_TYPE_BUTTON) {
indev->btn_points = points;
}
}
void lv_indev_get_point(const lv_indev_t * indev, lv_point_t * point)
{
if(indev == NULL) {
point->x = 0;
point->y = 0;
return;
}
if(indev->type != LV_INDEV_TYPE_POINTER && indev->type != LV_INDEV_TYPE_BUTTON) {
point->x = -1;
point->y = -1;
}
else {
point->x = indev->pointer.act_point.x;
point->y = indev->pointer.act_point.y;
}
}
lv_dir_t lv_indev_get_gesture_dir(const lv_indev_t * indev)
{
return indev->pointer.gesture_dir;
}
uint32_t lv_indev_get_key(const lv_indev_t * indev)
{
if(indev->type != LV_INDEV_TYPE_KEYPAD)
return 0;
else
return indev->keypad.last_key;
}
lv_dir_t lv_indev_get_scroll_dir(const lv_indev_t * indev)
{
if(indev == NULL) return false;
if(indev->type != LV_INDEV_TYPE_POINTER && indev->type != LV_INDEV_TYPE_BUTTON) return false;
return indev->pointer.scroll_dir;
}
lv_obj_t * lv_indev_get_scroll_obj(const lv_indev_t * indev)
{
if(indev == NULL) return NULL;
if(indev->type != LV_INDEV_TYPE_POINTER && indev->type != LV_INDEV_TYPE_BUTTON) return NULL;
return indev->pointer.scroll_obj;
}
void lv_indev_get_vect(const lv_indev_t * indev, lv_point_t * point)
{
point->x = 0;
point->y = 0;
if(indev == NULL) return;
if(indev->type == LV_INDEV_TYPE_POINTER || indev->type == LV_INDEV_TYPE_BUTTON) {
point->x = indev->pointer.vect.x;
point->y = indev->pointer.vect.y;
}
}
void lv_indev_wait_release(lv_indev_t * indev)
{
if(indev == NULL)return;
indev->wait_until_release = 1;
}
lv_obj_t * lv_indev_get_active_obj(void)
{
return indev_obj_act;
}
lv_timer_t * lv_indev_get_read_timer(lv_indev_t * indev)
{
if(!indev) {
LV_LOG_WARN("lv_indev_get_read_timer: indev was NULL");
return NULL;
}
return indev->read_timer;
}
lv_obj_t * lv_indev_search_obj(lv_obj_t * obj, lv_point_t * point)
{
lv_obj_t * found_p = NULL;
/*If this obj is hidden the children are hidden too so return immediately*/
if(lv_obj_has_flag(obj, LV_OBJ_FLAG_HIDDEN)) return NULL;
lv_point_t p_trans = *point;
lv_obj_transform_point(obj, &p_trans, false, true);
bool hit_test_ok = lv_obj_hit_test(obj, &p_trans);
/*If the point is on this object check its children too*/
lv_area_t obj_coords = obj->coords;
if(lv_obj_has_flag(obj, LV_OBJ_FLAG_OVERFLOW_VISIBLE)) {
int32_t ext_draw_size = _lv_obj_get_ext_draw_size(obj);
lv_area_increase(&obj_coords, ext_draw_size, ext_draw_size);
}
if(_lv_area_is_point_on(&obj_coords, &p_trans, 0)) {
int32_t i;
uint32_t child_cnt = lv_obj_get_child_cnt(obj);
/*If a child matches use it*/
for(i = child_cnt - 1; i >= 0; i--) {
lv_obj_t * child = obj->spec_attr->children[i];
found_p = lv_indev_search_obj(child, &p_trans);
if(found_p) return found_p;
}
}
/*If not return earlier for a clicked child and this obj's hittest was ok use it
*else return NULL*/
if(hit_test_ok) return obj;
else return NULL;
}
/**********************
* STATIC FUNCTIONS
**********************/
/**
* Process a new point from LV_INDEV_TYPE_POINTER input device
* @param i pointer to an input device
* @param data pointer to the data read from the input device
*/
static void indev_pointer_proc(lv_indev_t * i, lv_indev_data_t * data)
{
lv_display_t * disp = i->disp;
/*Save the raw points so they can be used again in indev_read_core*/
i->pointer.last_raw_point.x = data->point.x;
i->pointer.last_raw_point.y = data->point.y;
if(disp->rotation == LV_DISPLAY_ROTATION_180 || disp->rotation == LV_DISPLAY_ROTATION_270) {
data->point.x = disp->hor_res - data->point.x - 1;
data->point.y = disp->ver_res - data->point.y - 1;
}
if(disp->rotation == LV_DISPLAY_ROTATION_90 || disp->rotation == LV_DISPLAY_ROTATION_270) {
int32_t tmp = data->point.y;
data->point.y = data->point.x;
data->point.x = disp->ver_res - tmp - 1;
}
/*Simple sanity check*/
if(data->point.x < 0) {
LV_LOG_WARN("X is %d which is smaller than zero", (int)data->point.x);
}
if(data->point.x >= lv_display_get_horizontal_resolution(i->disp)) {
LV_LOG_WARN("X is %d which is greater than hor. res", (int)data->point.x);
}
if(data->point.y < 0) {
LV_LOG_WARN("Y is %d which is smaller than zero", (int)data->point.y);
}
if(data->point.y >= lv_display_get_vertical_resolution(i->disp)) {
LV_LOG_WARN("Y is %d which is greater than ver. res", (int)data->point.y);
}
/*Move the cursor if set and moved*/
if(i->cursor != NULL &&
(i->pointer.last_point.x != data->point.x || i->pointer.last_point.y != data->point.y)) {
lv_obj_set_pos(i->cursor, data->point.x, data->point.y);
}
i->pointer.act_point.x = data->point.x;
i->pointer.act_point.y = data->point.y;
if(i->state == LV_INDEV_STATE_PRESSED) {
indev_proc_press(i);
}
else {
indev_proc_release(i);
}
i->pointer.last_point.x = i->pointer.act_point.x;
i->pointer.last_point.y = i->pointer.act_point.y;
}
/**
* Process a new point from LV_INDEV_TYPE_KEYPAD input device
* @param i pointer to an input device
* @param data pointer to the data read from the input device
*/
static void indev_keypad_proc(lv_indev_t * i, lv_indev_data_t * data)
{
if(data->state == LV_INDEV_STATE_PRESSED && i->wait_until_release) return;
if(i->wait_until_release) {
i->wait_until_release = 0;
i->pr_timestamp = 0;
i->long_pr_sent = 0;
i->keypad.last_state = LV_INDEV_STATE_RELEASED; /*To skip the processing of release*/
}
lv_group_t * g = i->group;
if(g == NULL) return;
indev_obj_act = lv_group_get_focused(g);
if(indev_obj_act == NULL) return;
bool dis = lv_obj_has_state(indev_obj_act, LV_STATE_DISABLED);
/*Save the last key to compare it with the current latter on RELEASE*/
uint32_t prev_key = i->keypad.last_key;
/*Save the last key.
*It must be done here else `lv_indev_get_key` will return the last key in events*/
i->keypad.last_key = data->key;
/*Save the previous state so we can detect state changes below and also set the last state now
*so if any event handler on the way returns `LV_RESULT_INVALID` the last state is remembered
*for the next time*/
uint32_t prev_state = i->keypad.last_state;
i->keypad.last_state = data->state;
/*Key press happened*/
if(data->state == LV_INDEV_STATE_PRESSED && prev_state == LV_INDEV_STATE_RELEASED) {
LV_LOG_INFO("%" LV_PRIu32 " key is pressed", data->key);
i->pr_timestamp = lv_tick_get();
/*Move the focus on NEXT*/
if(data->key == LV_KEY_NEXT) {
lv_group_set_editing(g, false); /*Editing is not used by KEYPAD is be sure it is disabled*/
lv_group_focus_next(g);
if(indev_reset_check(i)) return;
}
/*Move the focus on PREV*/
else if(data->key == LV_KEY_PREV) {
lv_group_set_editing(g, false); /*Editing is not used by KEYPAD is be sure it is disabled*/
lv_group_focus_prev(g);
if(indev_reset_check(i)) return;
}
else if(!dis) {
/*Simulate a press on the object if ENTER was pressed*/
if(data->key == LV_KEY_ENTER) {
/*Send the ENTER as a normal KEY*/
lv_group_send_data(g, LV_KEY_ENTER);
if(indev_reset_check(i)) return;
if(!dis) lv_obj_send_event(indev_obj_act, LV_EVENT_PRESSED, indev_act);
if(indev_reset_check(i)) return;
}
else if(data->key == LV_KEY_ESC) {
/*Send the ESC as a normal KEY*/
lv_group_send_data(g, LV_KEY_ESC);
if(indev_reset_check(i)) return;
lv_obj_send_event(indev_obj_act, LV_EVENT_CANCEL, indev_act);
if(indev_reset_check(i)) return;
}
/*Just send other keys to the object (e.g. 'A' or `LV_GROUP_KEY_RIGHT`)*/
else {
lv_group_send_data(g, data->key);
if(indev_reset_check(i)) return;
}
}
}
/*Pressing*/
else if(!dis && data->state == LV_INDEV_STATE_PRESSED && prev_state == LV_INDEV_STATE_PRESSED) {
if(data->key == LV_KEY_ENTER) {
lv_obj_send_event(indev_obj_act, LV_EVENT_PRESSING, indev_act);
if(indev_reset_check(i)) return;
}
/*Long press time has elapsed?*/
if(i->long_pr_sent == 0 && lv_tick_elaps(i->pr_timestamp) > i->long_press_time) {
i->long_pr_sent = 1;
if(data->key == LV_KEY_ENTER) {
i->longpr_rep_timestamp = lv_tick_get();
if(!dis) lv_obj_send_event(indev_obj_act, LV_EVENT_LONG_PRESSED, indev_act);
if(indev_reset_check(i)) return;
}
}
/*Long press repeated time has elapsed?*/
else if(i->long_pr_sent != 0 &&
lv_tick_elaps(i->longpr_rep_timestamp) > i->long_press_repeat_time) {
i->longpr_rep_timestamp = lv_tick_get();
/*Send LONG_PRESS_REP on ENTER*/
if(data->key == LV_KEY_ENTER) {
if(!dis) lv_obj_send_event(indev_obj_act, LV_EVENT_LONG_PRESSED_REPEAT, indev_act);
if(indev_reset_check(i)) return;
}
/*Move the focus on NEXT again*/
else if(data->key == LV_KEY_NEXT) {
lv_group_set_editing(g, false); /*Editing is not used by KEYPAD is be sure it is disabled*/
lv_group_focus_next(g);
if(indev_reset_check(i)) return;
}
/*Move the focus on PREV again*/
else if(data->key == LV_KEY_PREV) {
lv_group_set_editing(g, false); /*Editing is not used by KEYPAD is be sure it is disabled*/
lv_group_focus_prev(g);
if(indev_reset_check(i)) return;
}
/*Just send other keys again to the object (e.g. 'A' or `LV_GROUP_KEY_RIGHT)*/
else {
lv_group_send_data(g, data->key);
if(indev_reset_check(i)) return;
}
}
}
/*Release happened*/
else if(!dis && data->state == LV_INDEV_STATE_RELEASED && prev_state == LV_INDEV_STATE_PRESSED) {
LV_LOG_INFO("%" LV_PRIu32 " key is released", data->key);
/*The user might clear the key when it was released. Always release the pressed key*/
data->key = prev_key;
if(data->key == LV_KEY_ENTER) {
if(!dis) lv_obj_send_event(indev_obj_act, LV_EVENT_RELEASED, indev_act);
if(indev_reset_check(i)) return;
if(i->long_pr_sent == 0) {
if(!dis) lv_obj_send_event(indev_obj_act, LV_EVENT_SHORT_CLICKED, indev_act);
if(indev_reset_check(i)) return;
}
if(!dis) lv_obj_send_event(indev_obj_act, LV_EVENT_CLICKED, indev_act);
if(indev_reset_check(i)) return;
}
i->pr_timestamp = 0;
i->long_pr_sent = 0;
}
indev_obj_act = NULL;
}
/**
* Process a new point from LV_INDEV_TYPE_ENCODER input device
* @param i pointer to an input device
* @param data pointer to the data read from the input device
*/
static void indev_encoder_proc(lv_indev_t * i, lv_indev_data_t * data)
{
if(data->state == LV_INDEV_STATE_PRESSED && i->wait_until_release) return;
if(i->wait_until_release) {
i->wait_until_release = 0;
i->pr_timestamp = 0;
i->long_pr_sent = 0;
i->keypad.last_state = LV_INDEV_STATE_RELEASED; /*To skip the processing of release*/
}
/*Save the last keys before anything else.
*They need to be already saved if the function returns for any reason*/
lv_indev_state_t last_state = i->keypad.last_state;
i->keypad.last_state = data->state;
i->keypad.last_key = data->key;
lv_group_t * g = i->group;
if(g == NULL) return;
indev_obj_act = lv_group_get_focused(g);
if(indev_obj_act == NULL) return;
/*Process the steps they are valid only with released button*/
if(data->state != LV_INDEV_STATE_RELEASED) {
data->enc_diff = 0;
}
/*Refresh the focused object. It might change due to lv_group_focus_prev/next*/
indev_obj_act = lv_group_get_focused(g);
if(indev_obj_act == NULL) return;
const bool is_disabled = lv_obj_has_state(indev_obj_act, LV_STATE_DISABLED);
/*Button press happened*/
if(data->state == LV_INDEV_STATE_PRESSED && last_state == LV_INDEV_STATE_RELEASED) {
LV_LOG_INFO("pressed");
i->pr_timestamp = lv_tick_get();
if(data->key == LV_KEY_ENTER) {
bool editable_or_scrollable = lv_obj_is_editable(indev_obj_act) ||
lv_obj_has_flag(indev_obj_act, LV_OBJ_FLAG_SCROLLABLE);
if(lv_group_get_editing(g) == true || editable_or_scrollable == false) {
if(!is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_PRESSED, indev_act);
if(indev_reset_check(i)) return;
}
}
else if(data->key == LV_KEY_LEFT) {
/*emulate encoder left*/
data->enc_diff--;
}
else if(data->key == LV_KEY_RIGHT) {
/*emulate encoder right*/
data->enc_diff++;
}
else if(data->key == LV_KEY_ESC) {
/*Send the ESC as a normal KEY*/
lv_group_send_data(g, LV_KEY_ESC);
if(indev_reset_check(i)) return;
lv_obj_send_event(indev_obj_act, LV_EVENT_CANCEL, indev_act);
if(indev_reset_check(i)) return;
}
/*Just send other keys to the object (e.g. 'A' or `LV_GROUP_KEY_RIGHT`)*/
else {
lv_group_send_data(g, data->key);
if(indev_reset_check(i)) return;
}
}
/*Pressing*/
else if(data->state == LV_INDEV_STATE_PRESSED && last_state == LV_INDEV_STATE_PRESSED) {
/*Long press*/
if(i->long_pr_sent == 0 && lv_tick_elaps(i->pr_timestamp) > i->long_press_time) {
i->long_pr_sent = 1;
i->longpr_rep_timestamp = lv_tick_get();
if(data->key == LV_KEY_ENTER) {
bool editable_or_scrollable = lv_obj_is_editable(indev_obj_act) ||
lv_obj_has_flag(indev_obj_act, LV_OBJ_FLAG_SCROLLABLE);
/*On enter long press toggle edit mode.*/
if(editable_or_scrollable) {
/*Don't leave edit mode if there is only one object (nowhere to navigate)*/
if(lv_group_get_obj_count(g) > 1) {
LV_LOG_INFO("toggling edit mode");
lv_group_set_editing(g, lv_group_get_editing(g) ? false : true); /*Toggle edit mode on long press*/
lv_obj_remove_state(indev_obj_act, LV_STATE_PRESSED); /*Remove the pressed state manually*/
}
}
/*If not editable then just send a long press Call the ancestor's event handler*/
else {
if(!is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_LONG_PRESSED, indev_act);
if(indev_reset_check(i)) return;
}
}
i->long_pr_sent = 1;
}
/*Long press repeated time has elapsed?*/
else if(i->long_pr_sent != 0 && lv_tick_elaps(i->longpr_rep_timestamp) > i->long_press_repeat_time) {
i->longpr_rep_timestamp = lv_tick_get();
if(data->key == LV_KEY_ENTER) {
if(!is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_LONG_PRESSED_REPEAT, indev_act);
if(indev_reset_check(i)) return;
}
else if(data->key == LV_KEY_LEFT) {
/*emulate encoder left*/
data->enc_diff--;
}
else if(data->key == LV_KEY_RIGHT) {
/*emulate encoder right*/
data->enc_diff++;
}
else {
lv_group_send_data(g, data->key);
if(indev_reset_check(i)) return;
}
}
}
/*Release happened*/
else if(data->state == LV_INDEV_STATE_RELEASED && last_state == LV_INDEV_STATE_PRESSED) {
LV_LOG_INFO("released");
if(data->key == LV_KEY_ENTER) {
bool editable_or_scrollable = lv_obj_is_editable(indev_obj_act) ||
lv_obj_has_flag(indev_obj_act, LV_OBJ_FLAG_SCROLLABLE);
/*The button was released on a non-editable object. Just send enter*/
if(editable_or_scrollable == false) {
if(!is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_RELEASED, indev_act);
if(indev_reset_check(i)) return;
if(i->long_pr_sent == 0 && !is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_SHORT_CLICKED, indev_act);
if(indev_reset_check(i)) return;
if(!is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_CLICKED, indev_act);
if(indev_reset_check(i)) return;
}
/*An object is being edited and the button is released.*/
else if(lv_group_get_editing(g)) {
/*Ignore long pressed enter release because it comes from mode switch*/
if(!i->long_pr_sent || lv_group_get_obj_count(g) <= 1) {
if(!is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_RELEASED, indev_act);
if(indev_reset_check(i)) return;
if(!is_disabled)lv_obj_send_event(indev_obj_act, LV_EVENT_SHORT_CLICKED, indev_act);
if(indev_reset_check(i)) return;
if(!is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_CLICKED, indev_act);
if(indev_reset_check(i)) return;
lv_group_send_data(g, LV_KEY_ENTER);
if(indev_reset_check(i)) return;
}
else {
lv_obj_remove_state(indev_obj_act, LV_STATE_PRESSED); /*Remove the pressed state manually*/
}
}
/*If the focused object is editable and now in navigate mode then on enter switch edit
mode*/
else if(!i->long_pr_sent) {
LV_LOG_INFO("entering edit mode");
lv_group_set_editing(g, true); /*Set edit mode*/
}
}
i->pr_timestamp = 0;
i->long_pr_sent = 0;
}
indev_obj_act = NULL;
/*if encoder steps or simulated steps via left/right keys*/
if(data->enc_diff != 0) {
/*In edit mode send LEFT/RIGHT keys*/
if(lv_group_get_editing(g)) {
LV_LOG_INFO("rotated by %+d (edit)", data->enc_diff);
int32_t s;
if(data->enc_diff < 0) {
for(s = 0; s < -data->enc_diff; s++) {
lv_group_send_data(g, LV_KEY_LEFT);
if(indev_reset_check(i)) return;
}
}
else if(data->enc_diff > 0) {
for(s = 0; s < data->enc_diff; s++) {
lv_group_send_data(g, LV_KEY_RIGHT);
if(indev_reset_check(i)) return;
}
}
}
/*In navigate mode focus on the next/prev objects*/
else {
LV_LOG_INFO("rotated by %+d (nav)", data->enc_diff);
int32_t s;
if(data->enc_diff < 0) {
for(s = 0; s < -data->enc_diff; s++) {
lv_group_focus_prev(g);
if(indev_reset_check(i)) return;
}
}
else if(data->enc_diff > 0) {
for(s = 0; s < data->enc_diff; s++) {
lv_group_focus_next(g);
if(indev_reset_check(i)) return;
}
}
}
}
}
/**
* Process new points from an input device. indev->state.pressed has to be set
* @param indev pointer to an input device state
* @param x x coordinate of the next point
* @param y y coordinate of the next point
*/
static void indev_button_proc(lv_indev_t * i, lv_indev_data_t * data)
{
/*Die gracefully if i->btn_points is NULL*/
if(i->btn_points == NULL) {
LV_LOG_WARN("btn_points is NULL");
return;
}
int32_t x = i->btn_points[data->btn_id].x;
int32_t y = i->btn_points[data->btn_id].y;
if(LV_INDEV_STATE_RELEASED != data->state) {
if(data->state == LV_INDEV_STATE_PRESSED) {
LV_LOG_INFO("button %" LV_PRIu32 " is pressed (x:%d y:%d)", data->btn_id, (int)x, (int)y);
}
else {
LV_LOG_INFO("button %" LV_PRIu32 " is released (x:%d y:%d)", data->btn_id, (int)x, (int)y);
}
}
/*If a new point comes always make a release*/
if(data->state == LV_INDEV_STATE_PRESSED) {
if(i->pointer.last_point.x != x ||
i->pointer.last_point.y != y) {
indev_proc_release(i);
}
}
if(indev_reset_check(i)) return;
/*Save the new points*/
i->pointer.act_point.x = x;
i->pointer.act_point.y = y;
if(data->state == LV_INDEV_STATE_PRESSED) indev_proc_press(i);
else indev_proc_release(i);
if(indev_reset_check(i)) return;
i->pointer.last_point.x = i->pointer.act_point.x;
i->pointer.last_point.y = i->pointer.act_point.y;
}
/**
* Process the pressed state of LV_INDEV_TYPE_POINTER input devices
* @param indev pointer to an input device 'proc'
*/
static void indev_proc_press(lv_indev_t * indev)
{
LV_LOG_INFO("pressed at x:%d y:%d", (int)indev->pointer.act_point.x,
(int)indev->pointer.act_point.y);
indev_obj_act = indev->pointer.act_obj;
if(indev->wait_until_release != 0) return;
lv_display_t * disp = indev_act->disp;
bool new_obj_searched = false;
/*If there is no last object then search*/
if(indev_obj_act == NULL) {
indev_obj_act = pointer_search_obj(disp, &indev->pointer.act_point);
new_obj_searched = true;
}
/*If there is an active object it's not scrolled and not protected also search*/
else if(indev->pointer.scroll_obj == NULL &&
lv_obj_has_flag(indev_obj_act, LV_OBJ_FLAG_PRESS_LOCK) == false) {
indev_obj_act = pointer_search_obj(disp, &indev->pointer.act_point);
new_obj_searched = true;
}
/*The last object might have scroll throw. Stop it manually*/
if(new_obj_searched && indev->pointer.last_obj) {
indev->pointer.scroll_throw_vect.x = 0;
indev->pointer.scroll_throw_vect.y = 0;
_lv_indev_scroll_throw_handler(indev);
if(indev_reset_check(indev)) return;
}
/*If a new object was found reset some variables and send a pressed event handler*/
if(indev_obj_act != indev->pointer.act_obj) {
indev->pointer.last_point.x = indev->pointer.act_point.x;
indev->pointer.last_point.y = indev->pointer.act_point.y;
/*If a new object found the previous was lost, so send a PRESS_LOST event*/
if(indev->pointer.act_obj != NULL) {
/*Save the obj because in special cases `act_obj` can change in the event */
lv_obj_t * last_obj = indev->pointer.act_obj;
lv_obj_send_event(last_obj, LV_EVENT_PRESS_LOST, indev_act);
if(indev_reset_check(indev)) return;
/*Do nothing until release and a new press*/
lv_indev_reset(indev, NULL);
lv_indev_wait_release(indev);
return;
}
indev->pointer.act_obj = indev_obj_act; /*Save the pressed object*/
indev->pointer.last_obj = indev_obj_act;
if(indev_obj_act != NULL) {
const bool is_disabled = lv_obj_has_state(indev_obj_act, LV_STATE_DISABLED);
/*Save the time when the obj pressed to count long press time.*/
indev->pr_timestamp = lv_tick_get();
indev->long_pr_sent = 0;
indev->pointer.scroll_sum.x = 0;
indev->pointer.scroll_sum.y = 0;
indev->pointer.scroll_dir = LV_DIR_NONE;
indev->pointer.gesture_dir = LV_DIR_NONE;
indev->pointer.gesture_sent = 0;
indev->pointer.gesture_sum.x = 0;
indev->pointer.gesture_sum.y = 0;
indev->pointer.vect.x = 0;
indev->pointer.vect.y = 0;
/*Call the ancestor's event handler about the press*/
if(!is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_PRESSED, indev_act);
if(indev_reset_check(indev)) return;
if(indev_act->wait_until_release) return;
/*Handle focus*/
indev_click_focus(indev_act);
if(indev_reset_check(indev)) return;
}
}
/*Calculate the vector and apply a low pass filter: new value = 0.5 * old_value + 0.5 * new_value*/
indev->pointer.vect.x = indev->pointer.act_point.x - indev->pointer.last_point.x;
indev->pointer.vect.y = indev->pointer.act_point.y - indev->pointer.last_point.y;
indev->pointer.scroll_throw_vect.x = (indev->pointer.scroll_throw_vect.x + indev->pointer.vect.x) / 2;
indev->pointer.scroll_throw_vect.y = (indev->pointer.scroll_throw_vect.y + indev->pointer.vect.y) / 2;
indev->pointer.scroll_throw_vect_ori = indev->pointer.scroll_throw_vect;
if(indev_obj_act) {
const bool is_disabled = lv_obj_has_state(indev_obj_act, LV_STATE_DISABLED);
lv_obj_send_event(indev_obj_act, LV_EVENT_PRESSING, indev_act);
if(indev_reset_check(indev)) return;
if(indev_act->wait_until_release) return;
_lv_indev_scroll_handler(indev);
if(indev_reset_check(indev)) return;
indev_gesture(indev);
if(indev_reset_check(indev)) return;
/*If there is no scrolling then check for long press time*/
if(indev->pointer.scroll_obj == NULL && indev->long_pr_sent == 0) {
/*Call the ancestor's event handler about the long press if enough time elapsed*/
if(lv_tick_elaps(indev->pr_timestamp) > indev_act->long_press_time) {
if(!is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_LONG_PRESSED, indev_act);
if(indev_reset_check(indev)) return;
/*Mark the Call the ancestor's event handler sending to do not send it again*/
indev->long_pr_sent = 1;
/*Save the long press time stamp for the long press repeat handler*/
indev->longpr_rep_timestamp = lv_tick_get();
}
}
/*Send long press repeated Call the ancestor's event handler*/
if(indev->pointer.scroll_obj == NULL && indev->long_pr_sent == 1) {
/*Call the ancestor's event handler about the long press repeat if enough time elapsed*/
if(lv_tick_elaps(indev->longpr_rep_timestamp) > indev_act->long_press_repeat_time) {
if(!is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_LONG_PRESSED_REPEAT, indev_act);
if(indev_reset_check(indev)) return;
indev->longpr_rep_timestamp = lv_tick_get();
}
}
}
}
/**
* Process the released state of LV_INDEV_TYPE_POINTER input devices
* @param proc pointer to an input device 'proc'
*/
static void indev_proc_release(lv_indev_t * indev)
{
if(indev->wait_until_release) {
lv_obj_send_event(indev->pointer.act_obj, LV_EVENT_PRESS_LOST, indev_act);
if(indev_reset_check(indev)) return;
indev->pointer.act_obj = NULL;
indev->pointer.last_obj = NULL;
indev->pr_timestamp = 0;
indev->longpr_rep_timestamp = 0;
indev->wait_until_release = 0;
}
indev_obj_act = indev->pointer.act_obj;
lv_obj_t * scroll_obj = indev->pointer.scroll_obj;
/*Forget the act obj and send a released Call the ancestor's event handler*/
if(indev_obj_act) {
LV_LOG_INFO("released");
const bool is_disabled = lv_obj_has_state(indev_obj_act, LV_STATE_DISABLED);
/*Send RELEASE Call the ancestor's event handler and event*/
if(!is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_RELEASED, indev_act);
if(indev_reset_check(indev)) return;
/*Send CLICK if no scrolling*/
if(scroll_obj == NULL) {
if(indev->long_pr_sent == 0) {
if(!is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_SHORT_CLICKED, indev_act);
if(indev_reset_check(indev)) return;
}
if(!is_disabled) lv_obj_send_event(indev_obj_act, LV_EVENT_CLICKED, indev_act);
if(indev_reset_check(indev)) return;
}
else {
lv_obj_send_event(scroll_obj, LV_EVENT_SCROLL_THROW_BEGIN, indev_act);
if(indev_reset_check(indev)) return;
}
indev->pointer.act_obj = NULL;
indev->pr_timestamp = 0;
indev->longpr_rep_timestamp = 0;
/*Get the transformed vector with this object*/
if(scroll_obj) {
int16_t angle = 0;
int16_t scale_x = 256;
int16_t scale_y = 256;
lv_point_t pivot = { 0, 0 };
lv_obj_t * parent = scroll_obj;
while(parent) {
angle += lv_obj_get_style_transform_rotation(parent, 0);
int32_t zoom_act_x = lv_obj_get_style_transform_scale_x_safe(parent, 0);
int32_t zoom_act_y = lv_obj_get_style_transform_scale_y_safe(parent, 0);
scale_x = (scale_x * zoom_act_x) >> 8;
scale_y = (scale_x * zoom_act_y) >> 8;
parent = lv_obj_get_parent(parent);
}
if(angle != 0 || scale_y != LV_SCALE_NONE || scale_x != LV_SCALE_NONE) {
angle = -angle;
scale_x = (256 * 256) / scale_x;
scale_y = (256 * 256) / scale_y;
lv_point_transform(&indev->pointer.scroll_throw_vect, angle, scale_x, scale_y, &pivot, false);
lv_point_transform(&indev->pointer.scroll_throw_vect_ori, angle, scale_x, scale_y, &pivot, false);
}
}
}
if(scroll_obj) {
_lv_indev_scroll_throw_handler(indev);
if(indev_reset_check(indev)) return;
}
}
static lv_obj_t * pointer_search_obj(lv_display_t * disp, lv_point_t * p)
{
indev_obj_act = lv_indev_search_obj(lv_display_get_layer_sys(disp), p);
if(indev_obj_act) return indev_obj_act;
indev_obj_act = lv_indev_search_obj(lv_display_get_layer_top(disp), p);
if(indev_obj_act) return indev_obj_act;
/* Search the object in the active screen */
indev_obj_act = lv_indev_search_obj(lv_display_get_screen_active(disp), p);
if(indev_obj_act) return indev_obj_act;
indev_obj_act = lv_indev_search_obj(lv_display_get_layer_bottom(disp), p);
return indev_obj_act;
}
/**
* Process a new point from LV_INDEV_TYPE_BUTTON input device
* @param i pointer to an input device
* @param data pointer to the data read from the input device
* Reset input device if a reset query has been sent to it
* @param indev pointer to an input device
*/
static void indev_proc_reset_query_handler(lv_indev_t * indev)
{
if(indev->reset_query) {
indev->pointer.act_obj = NULL;
indev->pointer.last_obj = NULL;
indev->pointer.scroll_obj = NULL;
indev->long_pr_sent = 0;
indev->pr_timestamp = 0;
indev->longpr_rep_timestamp = 0;
indev->pointer.scroll_sum.x = 0;
indev->pointer.scroll_sum.y = 0;
indev->pointer.scroll_dir = LV_DIR_NONE;
indev->pointer.scroll_throw_vect.x = 0;
indev->pointer.scroll_throw_vect.y = 0;
indev->pointer.gesture_sum.x = 0;
indev->pointer.gesture_sum.y = 0;
indev->reset_query = 0;
indev_obj_act = NULL;
}
}
/**
* Handle focus/defocus on click for POINTER input devices
* @param proc pointer to the state of the indev
*/
static void indev_click_focus(lv_indev_t * indev)
{
/*Handle click focus*/
if(lv_obj_has_flag(indev_obj_act, LV_OBJ_FLAG_CLICK_FOCUSABLE) == false) {
return;
}
lv_group_t * g_act = lv_obj_get_group(indev_obj_act);
lv_group_t * g_prev = indev->pointer.last_pressed ? lv_obj_get_group(indev->pointer.last_pressed) : NULL;
/*If both the last and act. obj. are in the same group (or have no group)*/
if(g_act == g_prev) {
/*The objects are in a group*/
if(g_act) {
lv_group_focus_obj(indev_obj_act);
if(indev_reset_check(indev)) return;
}
/*The object are not in group*/
else {
if(indev->pointer.last_pressed != indev_obj_act) {
lv_obj_send_event(indev->pointer.last_pressed, LV_EVENT_DEFOCUSED, indev_act);
if(indev_reset_check(indev)) return;
lv_obj_send_event(indev_obj_act, LV_EVENT_FOCUSED, indev_act);
if(indev_reset_check(indev)) return;
}
}
}
/*The object are not in the same group (in different groups or one has no group)*/
else {
/*If the prev. obj. is not in a group then defocus it.*/
if(g_prev == NULL && indev->pointer.last_pressed) {
lv_obj_send_event(indev->pointer.last_pressed, LV_EVENT_DEFOCUSED, indev_act);
if(indev_reset_check(indev)) return;
}
/*Focus on a non-group object*/
else {
if(indev->pointer.last_pressed) {
/*If the prev. object also wasn't in a group defocus it*/
if(g_prev == NULL) {
lv_obj_send_event(indev->pointer.last_pressed, LV_EVENT_DEFOCUSED, indev_act);
if(indev_reset_check(indev)) return;
}
/*If the prev. object also was in a group at least "LEAVE" it instead of defocus*/
else {
lv_obj_send_event(indev->pointer.last_pressed, LV_EVENT_LEAVE, indev_act);
if(indev_reset_check(indev)) return;
}
}
}
/*Focus to the act. in its group*/
if(g_act) {
lv_group_focus_obj(indev_obj_act);
if(indev_reset_check(indev)) return;
}
else {
lv_obj_send_event(indev_obj_act, LV_EVENT_FOCUSED, indev_act);
if(indev_reset_check(indev)) return;
}
}
indev->pointer.last_pressed = indev_obj_act;
}
/**
* Handle the gesture of indev_proc_p->pointer.act_obj
* @param indev pointer to an input device state
*/
void indev_gesture(lv_indev_t * indev)
{
if(indev->pointer.scroll_obj) return;
if(indev->pointer.gesture_sent) return;
lv_obj_t * gesture_obj = indev->pointer.act_obj;
/*If gesture parent is active check recursively the gesture attribute*/
while(gesture_obj && lv_obj_has_flag(gesture_obj, LV_OBJ_FLAG_GESTURE_BUBBLE)) {
gesture_obj = lv_obj_get_parent(gesture_obj);
}
if(gesture_obj == NULL) return;
if((LV_ABS(indev->pointer.vect.x) < indev_act->gesture_min_velocity) &&
(LV_ABS(indev->pointer.vect.y) < indev_act->gesture_min_velocity)) {
indev->pointer.gesture_sum.x = 0;
indev->pointer.gesture_sum.y = 0;
}
/*Count the movement by gesture*/
indev->pointer.gesture_sum.x += indev->pointer.vect.x;
indev->pointer.gesture_sum.y += indev->pointer.vect.y;
if((LV_ABS(indev->pointer.gesture_sum.x) > indev_act->gesture_limit) ||
(LV_ABS(indev->pointer.gesture_sum.y) > indev_act->gesture_limit)) {
indev->pointer.gesture_sent = 1;
if(LV_ABS(indev->pointer.gesture_sum.x) > LV_ABS(indev->pointer.gesture_sum.y)) {
if(indev->pointer.gesture_sum.x > 0)
indev->pointer.gesture_dir = LV_DIR_RIGHT;
else
indev->pointer.gesture_dir = LV_DIR_LEFT;
}
else {
if(indev->pointer.gesture_sum.y > 0)
indev->pointer.gesture_dir = LV_DIR_BOTTOM;
else
indev->pointer.gesture_dir = LV_DIR_TOP;
}
lv_obj_send_event(gesture_obj, LV_EVENT_GESTURE, indev_act);
if(indev_reset_check(indev)) return;
}
}
/**
* Checks if the reset_query flag has been set. If so, perform necessary global indev cleanup actions
* @param proc pointer to an input device 'proc'
* @return true if indev query should be immediately truncated.
*/
static bool indev_reset_check(lv_indev_t * indev)
{
if(indev->reset_query) {
indev_obj_act = NULL;
}
return indev->reset_query;
}
/**
* Reset the indev and send event to active obj and scroll obj
* @param indev pointer to an input device
* @param obj pointer to obj
*/
static void indev_reset_core(lv_indev_t * indev, lv_obj_t * obj)
{
lv_obj_t * act_obj = NULL;
lv_obj_t * scroll_obj = NULL;
indev->reset_query = 1;
if(indev_act == indev) indev_obj_act = NULL;
if(indev->type == LV_INDEV_TYPE_POINTER || indev->type == LV_INDEV_TYPE_KEYPAD) {
if(obj == NULL || indev->pointer.last_pressed == obj) {
indev->pointer.last_pressed = NULL;
}
if(obj == NULL || indev->pointer.act_obj == obj) {
if(indev->pointer.act_obj) {
/* Avoid recursive calls */
act_obj = indev->pointer.act_obj;
indev->pointer.act_obj = NULL;
lv_obj_send_event(act_obj, LV_EVENT_INDEV_RESET, indev);
act_obj = NULL;
}
}
if(obj == NULL || indev->pointer.last_obj == obj) {
indev->pointer.last_obj = NULL;
}
if(obj == NULL || indev->pointer.scroll_obj == obj) {
if(indev->pointer.scroll_obj) {
/* Avoid recursive calls */
scroll_obj = indev->pointer.scroll_obj;
indev->pointer.scroll_obj = NULL;
lv_obj_send_event(scroll_obj, LV_EVENT_INDEV_RESET, indev);
scroll_obj = NULL;
}
}
}
}
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/indev/lv_indev_scroll.h | /**
* @file lv_indev_scroll.h
*
*/
#ifndef LV_INDEV_SCROLL_H
#define LV_INDEV_SCROLL_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../core/lv_obj.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Handle scrolling. Called by LVGL during input device processing
* @param indev pointer to an input device
*/
void _lv_indev_scroll_handler(lv_indev_t * indev);
/**
* Handle throwing after scrolling. Called by LVGL during input device processing
* @param indev pointer to an input device
*/
void _lv_indev_scroll_throw_handler(lv_indev_t * indev);
/**
* Predict where would a scroll throw end
* @param indev pointer to an input device
* @param dir ` LV_DIR_VER` or `LV_DIR_HOR`
* @return the difference compared to the current position when the throw would be finished
*/
int32_t lv_indev_scroll_throw_predict(lv_indev_t * indev, lv_dir_t dir);
/**
* Get the distance of the nearest snap point
* @param obj the object on which snap points should be found
* @param p save the distance of the found snap point there
*/
void lv_indev_scroll_get_snap_dist(lv_obj_t * obj, lv_point_t * p);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_INDEV_SCROLL_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/indev/lv_indev_scroll.c | /**
* @file lv_indev_scroll.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_indev.h"
#include "lv_indev_private.h"
#include "lv_indev_scroll.h"
/*********************
* DEFINES
*********************/
#define ELASTIC_SLOWNESS_FACTOR 4 /*Scrolling on elastic parts are slower by this factor*/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static lv_obj_t * find_scroll_obj(lv_indev_t * indev);
static void init_scroll_limits(lv_indev_t * indev);
static int32_t find_snap_point_x(const lv_obj_t * obj, int32_t min, int32_t max, int32_t ofs);
static int32_t find_snap_point_y(const lv_obj_t * obj, int32_t min, int32_t max, int32_t ofs);
static void scroll_limit_diff(lv_indev_t * indev, int32_t * diff_x, int32_t * diff_y);
static int32_t scroll_throw_predict_y(lv_indev_t * indev);
static int32_t scroll_throw_predict_x(lv_indev_t * indev);
static int32_t elastic_diff(lv_obj_t * scroll_obj, int32_t diff, int32_t scroll_start, int32_t scroll_end,
lv_dir_t dir);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void _lv_indev_scroll_handler(lv_indev_t * indev)
{
if(indev->pointer.vect.x == 0 && indev->pointer.vect.y == 0) {
return;
}
lv_obj_t * scroll_obj = indev->pointer.scroll_obj;
/*If there is no scroll object yet try to find one*/
if(scroll_obj == NULL) {
scroll_obj = find_scroll_obj(indev);
if(scroll_obj == NULL) return;
init_scroll_limits(indev);
lv_obj_send_event(scroll_obj, LV_EVENT_SCROLL_BEGIN, NULL);
if(indev->reset_query) return;
}
/*Set new position or scroll if the vector is not zero*/
int16_t angle = 0;
int16_t scale_x = 256;
int16_t scale_y = 256;
lv_obj_t * parent = scroll_obj;
while(parent) {
angle += lv_obj_get_style_transform_rotation(parent, 0);
int32_t zoom_act_x = lv_obj_get_style_transform_scale_x_safe(parent, 0);
int32_t zoom_act_y = lv_obj_get_style_transform_scale_y_safe(parent, 0);
scale_x = (scale_x * zoom_act_x) >> 8;
scale_y = (scale_y * zoom_act_y) >> 8;
parent = lv_obj_get_parent(parent);
}
if(angle != 0 || scale_x != LV_SCALE_NONE || scale_y != LV_SCALE_NONE) {
angle = -angle;
scale_x = (256 * 256) / scale_x;
scale_y = (256 * 256) / scale_y;
lv_point_t pivot = { 0, 0 };
lv_point_transform(&indev->pointer.vect, angle, scale_x, scale_y, &pivot, false);
}
int32_t diff_x = 0;
int32_t diff_y = 0;
if(indev->pointer.scroll_dir == LV_DIR_HOR) {
int32_t sr = lv_obj_get_scroll_right(scroll_obj);
int32_t sl = lv_obj_get_scroll_left(scroll_obj);
diff_x = elastic_diff(scroll_obj, indev->pointer.vect.x, sl, sr, LV_DIR_HOR);
}
else {
int32_t st = lv_obj_get_scroll_top(scroll_obj);
int32_t sb = lv_obj_get_scroll_bottom(scroll_obj);
diff_y = elastic_diff(scroll_obj, indev->pointer.vect.y, st, sb, LV_DIR_VER);
}
lv_dir_t scroll_dir = lv_obj_get_scroll_dir(scroll_obj);
if((scroll_dir & LV_DIR_LEFT) == 0 && diff_x > 0) diff_x = 0;
if((scroll_dir & LV_DIR_RIGHT) == 0 && diff_x < 0) diff_x = 0;
if((scroll_dir & LV_DIR_TOP) == 0 && diff_y > 0) diff_y = 0;
if((scroll_dir & LV_DIR_BOTTOM) == 0 && diff_y < 0) diff_y = 0;
/*Respect the scroll limit area*/
scroll_limit_diff(indev, &diff_x, &diff_y);
_lv_obj_scroll_by_raw(scroll_obj, diff_x, diff_y);
if(indev->reset_query) return;
indev->pointer.scroll_sum.x += diff_x;
indev->pointer.scroll_sum.y += diff_y;
}
void _lv_indev_scroll_throw_handler(lv_indev_t * indev)
{
lv_obj_t * scroll_obj = indev->pointer.scroll_obj;
if(scroll_obj == NULL) return;
if(indev->pointer.scroll_dir == LV_DIR_NONE) return;
lv_indev_t * indev_act = lv_indev_active();
int32_t scroll_throw = indev_act->scroll_throw;
if(lv_obj_has_flag(scroll_obj, LV_OBJ_FLAG_SCROLL_MOMENTUM) == false) {
indev->pointer.scroll_throw_vect.y = 0;
indev->pointer.scroll_throw_vect.x = 0;
}
lv_scroll_snap_t align_x = lv_obj_get_scroll_snap_x(scroll_obj);
lv_scroll_snap_t align_y = lv_obj_get_scroll_snap_y(scroll_obj);
if(indev->pointer.scroll_dir == LV_DIR_VER) {
indev->pointer.scroll_throw_vect.x = 0;
/*If no snapping "throw"*/
if(align_y == LV_SCROLL_SNAP_NONE) {
indev->pointer.scroll_throw_vect.y =
indev->pointer.scroll_throw_vect.y * (100 - scroll_throw) / 100;
int32_t sb = lv_obj_get_scroll_bottom(scroll_obj);
int32_t st = lv_obj_get_scroll_top(scroll_obj);
indev->pointer.scroll_throw_vect.y = elastic_diff(scroll_obj, indev->pointer.scroll_throw_vect.y, st, sb,
LV_DIR_VER);
_lv_obj_scroll_by_raw(scroll_obj, 0, indev->pointer.scroll_throw_vect.y);
if(indev->reset_query) return;
}
/*With snapping find the nearest snap point and scroll there*/
else {
int32_t diff_y = scroll_throw_predict_y(indev);
indev->pointer.scroll_throw_vect.y = 0;
scroll_limit_diff(indev, NULL, &diff_y);
int32_t y = find_snap_point_y(scroll_obj, LV_COORD_MIN, LV_COORD_MAX, diff_y);
lv_obj_scroll_by(scroll_obj, 0, diff_y + y, LV_ANIM_ON);
if(indev->reset_query) return;
}
}
else if(indev->pointer.scroll_dir == LV_DIR_HOR) {
indev->pointer.scroll_throw_vect.y = 0;
/*If no snapping "throw"*/
if(align_x == LV_SCROLL_SNAP_NONE) {
indev->pointer.scroll_throw_vect.x =
indev->pointer.scroll_throw_vect.x * (100 - scroll_throw) / 100;
int32_t sl = lv_obj_get_scroll_left(scroll_obj);
int32_t sr = lv_obj_get_scroll_right(scroll_obj);
indev->pointer.scroll_throw_vect.x = elastic_diff(scroll_obj, indev->pointer.scroll_throw_vect.x, sl, sr,
LV_DIR_HOR);
_lv_obj_scroll_by_raw(scroll_obj, indev->pointer.scroll_throw_vect.x, 0);
if(indev->reset_query) return;
}
/*With snapping find the nearest snap point and scroll there*/
else {
int32_t diff_x = scroll_throw_predict_x(indev);
indev->pointer.scroll_throw_vect.x = 0;
scroll_limit_diff(indev, &diff_x, NULL);
int32_t x = find_snap_point_x(scroll_obj, LV_COORD_MIN, LV_COORD_MAX, diff_x);
lv_obj_scroll_by(scroll_obj, x + diff_x, 0, LV_ANIM_ON);
if(indev->reset_query) return;
}
}
/*Check if the scroll has finished*/
if(indev->pointer.scroll_throw_vect.x == 0 && indev->pointer.scroll_throw_vect.y == 0) {
/*Revert if scrolled in*/
/*If vertically scrollable and not controlled by snap*/
if(align_y == LV_SCROLL_SNAP_NONE) {
int32_t st = lv_obj_get_scroll_top(scroll_obj);
int32_t sb = lv_obj_get_scroll_bottom(scroll_obj);
if(st > 0 || sb > 0) {
if(st < 0) {
lv_obj_scroll_by(scroll_obj, 0, st, LV_ANIM_ON);
if(indev->reset_query) return;
}
else if(sb < 0) {
lv_obj_scroll_by(scroll_obj, 0, -sb, LV_ANIM_ON);
if(indev->reset_query) return;
}
}
}
/*If horizontally scrollable and not controlled by snap*/
if(align_x == LV_SCROLL_SNAP_NONE) {
int32_t sl = lv_obj_get_scroll_left(scroll_obj);
int32_t sr = lv_obj_get_scroll_right(scroll_obj);
if(sl > 0 || sr > 0) {
if(sl < 0) {
lv_obj_scroll_by(scroll_obj, sl, 0, LV_ANIM_ON);
if(indev->reset_query) return;
}
else if(sr < 0) {
lv_obj_scroll_by(scroll_obj, -sr, 0, LV_ANIM_ON);
if(indev->reset_query) return;
}
}
}
lv_obj_send_event(scroll_obj, LV_EVENT_SCROLL_END, indev_act);
if(indev->reset_query) return;
indev->pointer.scroll_dir = LV_DIR_NONE;
indev->pointer.scroll_obj = NULL;
}
}
/**
* Predict where would a scroll throw end
* @param indev pointer to an input device
* @param dir `LV_DIR_VER` or `LV_DIR_HOR`
* @return the difference compared to the current position when the throw would be finished
*/
int32_t lv_indev_scroll_throw_predict(lv_indev_t * indev, lv_dir_t dir)
{
if(indev == NULL) return 0;
int32_t v;
switch(dir) {
case LV_DIR_VER:
v = indev->pointer.scroll_throw_vect_ori.y;
break;
case LV_DIR_HOR:
v = indev->pointer.scroll_throw_vect_ori.x;
break;
default:
return 0;
}
int32_t scroll_throw = indev->scroll_throw;
int32_t sum = 0;
while(v) {
sum += v;
v = v * (100 - scroll_throw) / 100;
}
return sum;
}
void lv_indev_scroll_get_snap_dist(lv_obj_t * obj, lv_point_t * p)
{
p->x = find_snap_point_x(obj, obj->coords.x1, obj->coords.x2, 0);
p->y = find_snap_point_y(obj, obj->coords.y1, obj->coords.y2, 0);
}
/**********************
* STATIC FUNCTIONS
**********************/
static lv_obj_t * find_scroll_obj(lv_indev_t * indev)
{
lv_obj_t * obj_candidate = NULL;
lv_dir_t dir_candidate = LV_DIR_NONE;
lv_indev_t * indev_act = lv_indev_active();
int32_t scroll_limit = indev_act->scroll_limit;
/*Go until find a scrollable object in the current direction
*More precisely:
* 1. Check the pressed object and all of its ancestors and try to find an object which is scrollable
* 2. Scrollable means it has some content out of its area
* 3. If an object can be scrolled into the current direction then use it ("real match"")
* 4. If can be scrolled on the current axis (hor/ver) save it as candidate (at least show an elastic scroll effect)
* 5. Use the last candidate. Always the "deepest" parent or the object from point 3*/
lv_obj_t * obj_act = indev->pointer.act_obj;
/*Decide if it's a horizontal or vertical scroll*/
bool hor_en = false;
bool ver_en = false;
indev->pointer.scroll_sum.x += indev->pointer.vect.x;
indev->pointer.scroll_sum.y += indev->pointer.vect.y;
while(obj_act) {
/*Get the transformed scroll_sum with this object*/
int16_t angle = 0;
int32_t scale_x = 256;
int32_t scale_y = 256;
lv_point_t pivot = { 0, 0 };
lv_obj_t * parent = obj_act;
while(parent) {
angle += lv_obj_get_style_transform_rotation(parent, 0);
int32_t zoom_act_x = lv_obj_get_style_transform_scale_x_safe(parent, 0);
int32_t zoom_act_y = lv_obj_get_style_transform_scale_y_safe(parent, 0);
scale_x = (scale_x * zoom_act_x) >> 8;
scale_y = (scale_y * zoom_act_y) >> 8;
parent = lv_obj_get_parent(parent);
}
lv_point_t obj_scroll_sum = indev->pointer.scroll_sum;
if(angle != 0 || scale_x != LV_SCALE_NONE || scale_y != LV_SCALE_NONE) {
angle = -angle;
scale_x = (256 * 256) / scale_x;
scale_y = (256 * 256) / scale_y;
lv_point_transform(&obj_scroll_sum, angle, scale_x, scale_y, &pivot, false);
}
if(LV_ABS(obj_scroll_sum.x) > LV_ABS(obj_scroll_sum.y)) {
hor_en = true;
}
else {
ver_en = true;
}
if(lv_obj_has_flag(obj_act, LV_OBJ_FLAG_SCROLLABLE) == false) {
/*If this object don't want to chain the scroll to the parent stop searching*/
if(lv_obj_has_flag(obj_act, LV_OBJ_FLAG_SCROLL_CHAIN_HOR) == false && hor_en) break;
if(lv_obj_has_flag(obj_act, LV_OBJ_FLAG_SCROLL_CHAIN_VER) == false && ver_en) break;
obj_act = lv_obj_get_parent(obj_act);
continue;
}
/*Consider both up-down or left/right scrollable according to the current direction*/
bool up_en = ver_en;
bool down_en = ver_en;
bool left_en = hor_en;
bool right_en = hor_en;
/*The object might have disabled some directions.*/
lv_dir_t scroll_dir = lv_obj_get_scroll_dir(obj_act);
if((scroll_dir & LV_DIR_LEFT) == 0) left_en = false;
if((scroll_dir & LV_DIR_RIGHT) == 0) right_en = false;
if((scroll_dir & LV_DIR_TOP) == 0) up_en = false;
if((scroll_dir & LV_DIR_BOTTOM) == 0) down_en = false;
/*The object is scrollable to a direction if its content overflow in that direction.*/
int32_t st = lv_obj_get_scroll_top(obj_act);
int32_t sb = lv_obj_get_scroll_bottom(obj_act);
int32_t sl = lv_obj_get_scroll_left(obj_act);
int32_t sr = lv_obj_get_scroll_right(obj_act);
/*If this object is scrollable into the current scroll direction then save it as a candidate.
*It's important only to be scrollable on the current axis (hor/ver) because if the scroll
*is propagated to this object it can show at least elastic scroll effect.
*But if not hor/ver scrollable do not scroll it at all (so it's not a good candidate)*/
if((st > 0 || sb > 0) &&
((up_en && obj_scroll_sum.y >= scroll_limit) ||
(down_en && obj_scroll_sum.y <= - scroll_limit))) {
obj_candidate = obj_act;
dir_candidate = LV_DIR_VER;
}
if((sl > 0 || sr > 0) &&
((left_en && obj_scroll_sum.x >= scroll_limit) ||
(right_en && obj_scroll_sum.x <= - scroll_limit))) {
obj_candidate = obj_act;
dir_candidate = LV_DIR_HOR;
}
if(st <= 0) up_en = false;
if(sb <= 0) down_en = false;
if(sl <= 0) left_en = false;
if(sr <= 0) right_en = false;
/*If the object really can be scrolled into the current direction then use it.*/
if((left_en && obj_scroll_sum.x >= scroll_limit) ||
(right_en && obj_scroll_sum.x <= - scroll_limit) ||
(up_en && obj_scroll_sum.y >= scroll_limit) ||
(down_en && obj_scroll_sum.y <= - scroll_limit)) {
indev->pointer.scroll_dir = hor_en ? LV_DIR_HOR : LV_DIR_VER;
break;
}
/*If this object don't want to chain the scroll to the parent stop searching*/
if(lv_obj_has_flag(obj_act, LV_OBJ_FLAG_SCROLL_CHAIN_HOR) == false && hor_en) break;
if(lv_obj_has_flag(obj_act, LV_OBJ_FLAG_SCROLL_CHAIN_VER) == false && ver_en) break;
/*Try the parent*/
obj_act = lv_obj_get_parent(obj_act);
}
/*Use the last candidate*/
if(obj_candidate) {
indev->pointer.scroll_dir = dir_candidate;
indev->pointer.scroll_obj = obj_candidate;
indev->pointer.scroll_sum.x = 0;
indev->pointer.scroll_sum.y = 0;
}
return obj_candidate;
}
static void init_scroll_limits(lv_indev_t * indev)
{
lv_obj_t * obj = indev->pointer.scroll_obj;
/*If there no STOP allow scrolling anywhere*/
if(lv_obj_has_flag(obj, LV_OBJ_FLAG_SCROLL_ONE) == false) {
lv_area_set(&indev->pointer.scroll_area, LV_COORD_MIN, LV_COORD_MIN, LV_COORD_MAX, LV_COORD_MAX);
}
/*With STOP limit the scrolling to the perv and next snap point*/
else {
switch(lv_obj_get_scroll_snap_y(obj)) {
case LV_SCROLL_SNAP_START:
indev->pointer.scroll_area.y1 = find_snap_point_y(obj, obj->coords.y1 + 1, LV_COORD_MAX, 0);
indev->pointer.scroll_area.y2 = find_snap_point_y(obj, LV_COORD_MIN, obj->coords.y1 - 1, 0);
break;
case LV_SCROLL_SNAP_END:
indev->pointer.scroll_area.y1 = find_snap_point_y(obj, obj->coords.y2, LV_COORD_MAX, 0);
indev->pointer.scroll_area.y2 = find_snap_point_y(obj, LV_COORD_MIN, obj->coords.y2, 0);
break;
case LV_SCROLL_SNAP_CENTER: {
int32_t y_mid = obj->coords.y1 + lv_area_get_height(&obj->coords) / 2;
indev->pointer.scroll_area.y1 = find_snap_point_y(obj, y_mid + 1, LV_COORD_MAX, 0);
indev->pointer.scroll_area.y2 = find_snap_point_y(obj, LV_COORD_MIN, y_mid - 1, 0);
break;
}
default:
indev->pointer.scroll_area.y1 = LV_COORD_MIN;
indev->pointer.scroll_area.y2 = LV_COORD_MAX;
break;
}
switch(lv_obj_get_scroll_snap_x(obj)) {
case LV_SCROLL_SNAP_START:
indev->pointer.scroll_area.x1 = find_snap_point_x(obj, obj->coords.x1, LV_COORD_MAX, 0);
indev->pointer.scroll_area.x2 = find_snap_point_x(obj, LV_COORD_MIN, obj->coords.x1, 0);
break;
case LV_SCROLL_SNAP_END:
indev->pointer.scroll_area.x1 = find_snap_point_x(obj, obj->coords.x2, LV_COORD_MAX, 0);
indev->pointer.scroll_area.x2 = find_snap_point_x(obj, LV_COORD_MIN, obj->coords.x2, 0);
break;
case LV_SCROLL_SNAP_CENTER: {
int32_t x_mid = obj->coords.x1 + lv_area_get_width(&obj->coords) / 2;
indev->pointer.scroll_area.x1 = find_snap_point_x(obj, x_mid + 1, LV_COORD_MAX, 0);
indev->pointer.scroll_area.x2 = find_snap_point_x(obj, LV_COORD_MIN, x_mid - 1, 0);
break;
}
default:
indev->pointer.scroll_area.x1 = LV_COORD_MIN;
indev->pointer.scroll_area.x2 = LV_COORD_MAX;
break;
}
}
/*Allow scrolling on the edges. It will be reverted to the edge due to snapping anyway*/
if(indev->pointer.scroll_area.x1 == 0) indev->pointer.scroll_area.x1 = LV_COORD_MIN;
if(indev->pointer.scroll_area.x2 == 0) indev->pointer.scroll_area.x2 = LV_COORD_MAX;
if(indev->pointer.scroll_area.y1 == 0) indev->pointer.scroll_area.y1 = LV_COORD_MIN;
if(indev->pointer.scroll_area.y2 == 0) indev->pointer.scroll_area.y2 = LV_COORD_MAX;
}
/**
* Search for snap point in the `min` - `max` range.
* @param obj the object on which snap point should be found
* @param min ignore snap points smaller than this. (Absolute coordinate)
* @param max ignore snap points greater than this. (Absolute coordinate)
* @param ofs offset to snap points. Useful the get a snap point in an imagined case
* what if children are already moved by this value
* @return the distance of the snap point.
*/
static int32_t find_snap_point_x(const lv_obj_t * obj, int32_t min, int32_t max, int32_t ofs)
{
lv_scroll_snap_t align = lv_obj_get_scroll_snap_x(obj);
if(align == LV_SCROLL_SNAP_NONE) return 0;
int32_t dist = LV_COORD_MAX;
int32_t pad_left = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
int32_t pad_right = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
uint32_t i;
uint32_t child_cnt = lv_obj_get_child_cnt(obj);
for(i = 0; i < child_cnt; i++) {
lv_obj_t * child = obj->spec_attr->children[i];
if(lv_obj_has_flag_any(child, LV_OBJ_FLAG_HIDDEN | LV_OBJ_FLAG_FLOATING)) continue;
if(lv_obj_has_flag(child, LV_OBJ_FLAG_SNAPPABLE)) {
int32_t x_child = 0;
int32_t x_parent = 0;
switch(align) {
case LV_SCROLL_SNAP_START:
x_child = child->coords.x1;
x_parent = obj->coords.x1 + pad_left;
break;
case LV_SCROLL_SNAP_END:
x_child = child->coords.x2;
x_parent = obj->coords.x2 - pad_right;
break;
case LV_SCROLL_SNAP_CENTER:
x_child = child->coords.x1 + lv_area_get_width(&child->coords) / 2;
x_parent = obj->coords.x1 + pad_left + (lv_area_get_width(&obj->coords) - pad_left - pad_right) / 2;
break;
default:
continue;
}
x_child += ofs;
if(x_child >= min && x_child <= max) {
int32_t x = x_child - x_parent;
if(LV_ABS(x) < LV_ABS(dist)) dist = x;
}
}
}
return dist == LV_COORD_MAX ? 0 : -dist;
}
/**
* Search for snap point in the `min` - `max` range.
* @param obj the object on which snap point should be found
* @param min ignore snap points smaller than this. (Absolute coordinate)
* @param max ignore snap points greater than this. (Absolute coordinate)
* @param ofs offset to snap points. Useful to get a snap point in an imagined case
* what if children are already moved by this value
* @return the distance of the snap point.
*/
static int32_t find_snap_point_y(const lv_obj_t * obj, int32_t min, int32_t max, int32_t ofs)
{
lv_scroll_snap_t align = lv_obj_get_scroll_snap_y(obj);
if(align == LV_SCROLL_SNAP_NONE) return 0;
int32_t dist = LV_COORD_MAX;
int32_t pad_top = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
int32_t pad_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN);
uint32_t i;
uint32_t child_cnt = lv_obj_get_child_cnt(obj);
for(i = 0; i < child_cnt; i++) {
lv_obj_t * child = obj->spec_attr->children[i];
if(lv_obj_has_flag_any(child, LV_OBJ_FLAG_HIDDEN | LV_OBJ_FLAG_FLOATING)) continue;
if(lv_obj_has_flag(child, LV_OBJ_FLAG_SNAPPABLE)) {
int32_t y_child = 0;
int32_t y_parent = 0;
switch(align) {
case LV_SCROLL_SNAP_START:
y_child = child->coords.y1;
y_parent = obj->coords.y1 + pad_top;
break;
case LV_SCROLL_SNAP_END:
y_child = child->coords.y2;
y_parent = obj->coords.y2 - pad_bottom;
break;
case LV_SCROLL_SNAP_CENTER:
y_child = child->coords.y1 + lv_area_get_height(&child->coords) / 2;
y_parent = obj->coords.y1 + pad_top + (lv_area_get_height(&obj->coords) - pad_top - pad_bottom) / 2;
break;
default:
continue;
}
y_child += ofs;
if(y_child >= min && y_child <= max) {
int32_t y = y_child - y_parent;
if(LV_ABS(y) < LV_ABS(dist)) dist = y;
}
}
}
return dist == LV_COORD_MAX ? 0 : -dist;
}
static void scroll_limit_diff(lv_indev_t * indev, int32_t * diff_x, int32_t * diff_y)
{
if(diff_y) {
if(indev->pointer.scroll_sum.y + *diff_y < indev->pointer.scroll_area.y1) {
*diff_y = indev->pointer.scroll_area.y1 - indev->pointer.scroll_sum.y;
}
if(indev->pointer.scroll_sum.y + *diff_y > indev->pointer.scroll_area.y2) {
*diff_y = indev->pointer.scroll_area.y2 - indev->pointer.scroll_sum.y;
}
}
if(diff_x) {
if(indev->pointer.scroll_sum.x + *diff_x < indev->pointer.scroll_area.x1) {
*diff_x = indev->pointer.scroll_area.x1 - indev->pointer.scroll_sum.x;
}
if(indev->pointer.scroll_sum.x + *diff_x > indev->pointer.scroll_area.x2) {
*diff_x = indev->pointer.scroll_area.x2 - indev->pointer.scroll_sum.x;
}
}
}
static int32_t scroll_throw_predict_y(lv_indev_t * indev)
{
int32_t y = indev->pointer.scroll_throw_vect.y;
int32_t move = 0;
lv_indev_t * indev_act = lv_indev_active();
int32_t scroll_throw = indev_act->scroll_throw;
while(y) {
move += y;
y = y * (100 - scroll_throw) / 100;
}
return move;
}
static int32_t scroll_throw_predict_x(lv_indev_t * indev)
{
int32_t x = indev->pointer.scroll_throw_vect.x;
int32_t move = 0;
lv_indev_t * indev_act = lv_indev_active();
int32_t scroll_throw = indev_act->scroll_throw;
while(x) {
move += x;
x = x * (100 - scroll_throw) / 100;
}
return move;
}
static int32_t elastic_diff(lv_obj_t * scroll_obj, int32_t diff, int32_t scroll_start, int32_t scroll_end,
lv_dir_t dir)
{
if(lv_obj_has_flag(scroll_obj, LV_OBJ_FLAG_SCROLL_ELASTIC)) {
/*If there is snapping in the current direction don't use the elastic factor because
*it's natural that the first and last items are scrolled (snapped) in.*/
lv_scroll_snap_t snap;
snap = dir == LV_DIR_HOR ? lv_obj_get_scroll_snap_x(scroll_obj) : lv_obj_get_scroll_snap_y(scroll_obj);
lv_obj_t * act_obj = lv_indev_get_active_obj();
int32_t snap_point = 0;
int32_t act_obj_point = 0;
if(dir == LV_DIR_HOR) {
int32_t pad_left = lv_obj_get_style_pad_left(scroll_obj, LV_PART_MAIN);
int32_t pad_right = lv_obj_get_style_pad_right(scroll_obj, LV_PART_MAIN);
switch(snap) {
case LV_SCROLL_SNAP_CENTER:
snap_point = pad_left + (lv_area_get_width(&scroll_obj->coords) - pad_left - pad_right) / 2 + scroll_obj->coords.x1;
act_obj_point = lv_area_get_width(&act_obj->coords) / 2 + act_obj->coords.x1;
break;
case LV_SCROLL_SNAP_START:
snap_point = scroll_obj->coords.x1 + pad_left;
act_obj_point = act_obj->coords.x1;
break;
case LV_SCROLL_SNAP_END:
snap_point = scroll_obj->coords.x2 - pad_right;
act_obj_point = act_obj->coords.x2;
break;
}
}
else {
int32_t pad_top = lv_obj_get_style_pad_top(scroll_obj, LV_PART_MAIN);
int32_t pad_bottom = lv_obj_get_style_pad_bottom(scroll_obj, LV_PART_MAIN);
switch(snap) {
case LV_SCROLL_SNAP_CENTER:
snap_point = pad_top + (lv_area_get_height(&scroll_obj->coords) - pad_top - pad_bottom) / 2 + scroll_obj->coords.y1;
act_obj_point = lv_area_get_height(&act_obj->coords) / 2 + act_obj->coords.y1;
break;
case LV_SCROLL_SNAP_START:
snap_point = scroll_obj->coords.y1 + pad_top;
act_obj_point = act_obj->coords.y1;
break;
case LV_SCROLL_SNAP_END:
snap_point = scroll_obj->coords.y2 - pad_bottom;
act_obj_point = act_obj->coords.y2;
break;
}
}
if(scroll_end < 0) {
if(snap != LV_SCROLL_SNAP_NONE && act_obj_point > snap_point) return diff;
/*Rounding*/
if(diff < 0) diff -= ELASTIC_SLOWNESS_FACTOR / 2;
if(diff > 0) diff += ELASTIC_SLOWNESS_FACTOR / 2;
return diff / ELASTIC_SLOWNESS_FACTOR;
}
else if(scroll_start < 0) {
if(snap != LV_SCROLL_SNAP_NONE && act_obj_point < snap_point) return diff;
/*Rounding*/
if(diff < 0) diff -= ELASTIC_SLOWNESS_FACTOR / 2;
if(diff > 0) diff += ELASTIC_SLOWNESS_FACTOR / 2;
return diff / ELASTIC_SLOWNESS_FACTOR;
}
}
else {
/*Scroll back to the boundary if required*/
if(scroll_end + diff < 0) diff = - scroll_end;
if(scroll_start - diff < 0) diff = scroll_start;
}
return diff;
}
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/indev/lv_indev_private.h | /**
* @file lv_indev_private.h
*
*/
#ifndef LV_INDEV_PRIVATE_H
#define LV_INDEV_PRIVATE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "lv_indev.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
struct _lv_indev_t;
struct _lv_event_t;
struct _lv_indev_t {
/**< Input device type*/
lv_indev_type_t type;
/**< Function pointer to read input device data.*/
lv_indev_read_cb_t read_cb;
/** Called when an action happened on the input device.
* The second parameter is the event structure pointer*/
void (*feedback_cb)(struct _lv_indev_t * indev, struct _lv_event_t * e);
lv_indev_state_t state; /**< Current state of the input device.*/
/*Flags*/
uint8_t long_pr_sent : 1;
uint8_t reset_query : 1;
uint8_t disabled : 1;
uint8_t wait_until_release : 1;
uint32_t pr_timestamp; /**< Pressed time stamp*/
uint32_t longpr_rep_timestamp; /**< Long press repeat time stamp*/
void * driver_data;
void * user_data;
/**< Pointer to the assigned display*/
struct _lv_display_t * disp;
/**< Timer to periodically read the input device*/
lv_timer_t * read_timer;
/**< Number of pixels to slide before actually drag the object*/
uint8_t scroll_limit;
/**< Drag throw slow-down in [%]. Greater value means faster slow-down*/
uint8_t scroll_throw;
/**< At least this difference should be between two points to evaluate as gesture*/
uint8_t gesture_min_velocity;
/**< At least this difference should be to send a gesture*/
uint8_t gesture_limit;
/**< Long press time in milliseconds*/
uint16_t long_press_time;
/**< Repeated trigger period in long press [ms]*/
uint16_t long_press_repeat_time;
struct {
/*Pointer and button data*/
lv_point_t act_point; /**< Current point of input device.*/
lv_point_t last_point; /**< Last point of input device.*/
lv_point_t last_raw_point; /**< Last point read from read_cb. */
lv_point_t vect; /**< Difference between `act_point` and `last_point`.*/
lv_point_t scroll_sum; /*Count the dragged pixels to check LV_INDEV_DEF_SCROLL_LIMIT*/
lv_point_t scroll_throw_vect;
lv_point_t scroll_throw_vect_ori;
struct _lv_obj_t * act_obj; /*The object being pressed*/
struct _lv_obj_t * last_obj; /*The last object which was pressed*/
struct _lv_obj_t * scroll_obj; /*The object being scrolled*/
struct _lv_obj_t * last_pressed; /*The lastly pressed object*/
lv_area_t scroll_area;
lv_point_t gesture_sum; /*Count the gesture pixels to check LV_INDEV_DEF_GESTURE_LIMIT*/
/*Flags*/
lv_dir_t scroll_dir : 4;
lv_dir_t gesture_dir : 4;
uint8_t gesture_sent : 1;
} pointer;
struct {
/*Keypad data*/
lv_indev_state_t last_state;
uint32_t last_key;
} keypad;
struct _lv_obj_t * cursor; /**< Cursor for LV_INPUT_TYPE_POINTER*/
struct _lv_group_t * group; /**< Keypad destination group*/
const lv_point_t * btn_points; /**< Array points assigned to the button ()screen will be pressed
here by the buttons*/
};
/**********************
* GLOBAL PROTOTYPES
**********************/
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_INDEV_PRIVATE_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/indev/lv_indev.h | /**
* @file lv_indev.h
*
*/
#ifndef LV_INDEV_H
#define LV_INDEV_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../core/lv_group.h"
#include "../misc/lv_area.h"
#include "../misc/lv_timer.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
struct _lv_obj_t;
struct _lv_display_t;
struct _lv_group_t;
struct _lv_indev_t;
struct _lv_display_t;
typedef struct _lv_indev_t lv_indev_t;
/** Possible input device types*/
typedef enum {
LV_INDEV_TYPE_NONE, /**< Uninitialized state*/
LV_INDEV_TYPE_POINTER, /**< Touch pad, mouse, external button*/
LV_INDEV_TYPE_KEYPAD, /**< Keypad or keyboard*/
LV_INDEV_TYPE_BUTTON, /**< External (hardware button) which is assigned to a specific point of the screen*/
LV_INDEV_TYPE_ENCODER, /**< Encoder with only Left, Right turn and a Button*/
} lv_indev_type_t;
/** States for input devices*/
typedef enum {
LV_INDEV_STATE_RELEASED = 0,
LV_INDEV_STATE_PRESSED
} lv_indev_state_t;
/** Data structure passed to an input driver to fill*/
typedef struct {
lv_point_t point; /**< For LV_INDEV_TYPE_POINTER the currently pressed point*/
uint32_t key; /**< For LV_INDEV_TYPE_KEYPAD the currently pressed key*/
uint32_t btn_id; /**< For LV_INDEV_TYPE_BUTTON the currently pressed button*/
int16_t enc_diff; /**< For LV_INDEV_TYPE_ENCODER number of steps since the previous read*/
lv_indev_state_t state; /**< LV_INDEV_STATE_REL or LV_INDEV_STATE_PR*/
bool continue_reading; /**< If set to true, the read callback is invoked again*/
} lv_indev_data_t;
typedef void (*lv_indev_read_cb_t)(struct _lv_indev_t * indev, lv_indev_data_t * data);
/**********************
* GLOBAL PROTOTYPES
**********************/
lv_indev_t * lv_indev_create(void);
/**
* Remove the provided input device. Make sure not to use the provided input device afterwards anymore.
* @param indev pointer to delete
*/
void lv_indev_delete(lv_indev_t * indev);
/**
* Get the next input device.
* @param indev pointer to the current input device. NULL to initialize.
* @return the next input device or NULL if there are no more. Provide the first input device when
* the parameter is NULL
*/
lv_indev_t * lv_indev_get_next(lv_indev_t * indev);
/**
* Read data from an input device.
* @param indev pointer to an input device
*/
void lv_indev_read(lv_indev_t * indev);
/**
* Called periodically to read the input devices
* @param timer pointer to a timer to read
*/
void lv_indev_read_timer_cb(lv_timer_t * timer);
/**
* Enable or disable one or all input devices (default enabled)
* @param indev pointer to an input device or NULL to enable/disable all of them
* @param en true to enable, false to disable
*/
void lv_indev_enable(lv_indev_t * indev, bool en);
/**
* Get the currently processed input device. Can be used in action functions too.
* @return pointer to the currently processed input device or NULL if no input device processing
* right now
*/
lv_indev_t * lv_indev_active(void);
/**
* Set the type of an input device
* @param indev pointer to an input device
* @param indev_type the type of the input device from `lv_indev_type_t` (`LV_INDEV_TYPE_...`)
*/
void lv_indev_set_type(lv_indev_t * indev, lv_indev_type_t indev_type);
void lv_indev_set_read_cb(lv_indev_t * indev, lv_indev_read_cb_t read_cb);
void lv_indev_set_user_data(lv_indev_t * indev, void * user_data);
void lv_indev_set_driver_data(lv_indev_t * indev, void * driver_data);
/**
* Get the type of an input device
* @param indev pointer to an input device
* @return the type of the input device from `lv_hal_indev_type_t` (`LV_INDEV_TYPE_...`)
*/
lv_indev_type_t lv_indev_get_type(const lv_indev_t * indev);
lv_indev_state_t lv_indev_get_state(const lv_indev_t * indev);
lv_group_t * lv_indev_get_group(const lv_indev_t * indev);
struct _lv_display_t * lv_indev_get_disp(const lv_indev_t * indev);
void lv_indev_set_disp(lv_indev_t * indev, struct _lv_display_t * disp);
void * lv_indev_get_user_data(const lv_indev_t * indev);
void * lv_indev_get_driver_data(const lv_indev_t * indev);
/**
* Reset one or all input devices
* @param indev pointer to an input device to reset or NULL to reset all of them
* @param obj pointer to an object which triggers the reset.
*/
void lv_indev_reset(lv_indev_t * indev, struct _lv_obj_t * obj);
/**
* Reset the long press state of an input device
* @param indev pointer to an input device
*/
void lv_indev_reset_long_press(lv_indev_t * indev);
/**
* Set a cursor for a pointer input device (for LV_INPUT_TYPE_POINTER and LV_INPUT_TYPE_BUTTON)
* @param indev pointer to an input device
* @param cur_obj pointer to an object to be used as cursor
*/
void lv_indev_set_cursor(lv_indev_t * indev, struct _lv_obj_t * cur_obj);
/**
* Set a destination group for a keypad input device (for LV_INDEV_TYPE_KEYPAD)
* @param indev pointer to an input device
* @param group pointer to a group
*/
void lv_indev_set_group(lv_indev_t * indev, lv_group_t * group);
/**
* Set the an array of points for LV_INDEV_TYPE_BUTTON.
* These points will be assigned to the buttons to press a specific point on the screen
* @param indev pointer to an input device
* @param points array of points
*/
void lv_indev_set_button_points(lv_indev_t * indev, const lv_point_t points[]);
/**
* Get the last point of an input device (for LV_INDEV_TYPE_POINTER and LV_INDEV_TYPE_BUTTON)
* @param indev pointer to an input device
* @param point pointer to a point to store the result
*/
void lv_indev_get_point(const lv_indev_t * indev, lv_point_t * point);
/**
* Get the current gesture direct
* @param indev pointer to an input device
* @return current gesture direct
*/
lv_dir_t lv_indev_get_gesture_dir(const lv_indev_t * indev);
/**
* Get the last pressed key of an input device (for LV_INDEV_TYPE_KEYPAD)
* @param indev pointer to an input device
* @return the last pressed key (0 on error)
*/
uint32_t lv_indev_get_key(const lv_indev_t * indev);
/**
* Check the current scroll direction of an input device (for LV_INDEV_TYPE_POINTER and
* LV_INDEV_TYPE_BUTTON)
* @param indev pointer to an input device
* @return LV_DIR_NONE: no scrolling now
* LV_DIR_HOR/VER
*/
lv_dir_t lv_indev_get_scroll_dir(const lv_indev_t * indev);
/**
* Get the currently scrolled object (for LV_INDEV_TYPE_POINTER and
* LV_INDEV_TYPE_BUTTON)
* @param indev pointer to an input device
* @return pointer to the currently scrolled object or NULL if no scrolling by this indev
*/
struct _lv_obj_t * lv_indev_get_scroll_obj(const lv_indev_t * indev);
/**
* Get the movement vector of an input device (for LV_INDEV_TYPE_POINTER and
* LV_INDEV_TYPE_BUTTON)
* @param indev pointer to an input device
* @param point pointer to a point to store the types.pointer.vector
*/
void lv_indev_get_vect(const lv_indev_t * indev, lv_point_t * point);
/**
* Do nothing until the next release
* @param indev pointer to an input device
*/
void lv_indev_wait_release(lv_indev_t * indev);
/**
* Gets a pointer to the currently active object in the currently processed input device.
* @return pointer to currently active object or NULL if no active object
*/
struct _lv_obj_t * lv_indev_get_active_obj(void);
/**
* Get a pointer to the indev read timer to
* modify its parameters with `lv_timer_...` functions.
* @param indev pointer to an input device
* @return pointer to the indev read refresher timer. (NULL on error)
*/
lv_timer_t * lv_indev_get_read_timer(lv_indev_t * indev);
/**
* Search the most top, clickable object by a point
* @param obj pointer to a start object, typically the screen
* @param point pointer to a point for searching the most top child
* @return pointer to the found object or NULL if there was no suitable object
*/
struct _lv_obj_t * lv_indev_search_obj(struct _lv_obj_t * obj, lv_point_t * point);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_INDEV_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/fragment/lv_fragment.c | /**
* @file lv_fragment.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_fragment.h"
#if LV_USE_FRAGMENT
#include "../../stdlib/lv_string.h"
/**********************
* STATIC PROTOTYPES
**********************/
static void cb_delete_assertion(lv_event_t * event);
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_fragment_t * lv_fragment_create(const lv_fragment_class_t * cls, void * args)
{
LV_ASSERT_NULL(cls);
LV_ASSERT_NULL(cls->create_obj_cb);
LV_ASSERT(cls->instance_size >= sizeof(lv_fragment_t));
lv_fragment_t * instance = lv_malloc(cls->instance_size);
lv_memzero(instance, cls->instance_size);
instance->cls = cls;
instance->child_manager = lv_fragment_manager_create(instance);
if(cls->constructor_cb) {
cls->constructor_cb(instance, args);
}
return instance;
}
void lv_fragment_delete(lv_fragment_t * fragment)
{
LV_ASSERT_NULL(fragment);
if(fragment->managed) {
lv_fragment_manager_remove(fragment->managed->manager, fragment);
return;
}
if(fragment->obj) {
lv_fragment_delete_obj(fragment);
}
/* Objects will leak if this function called before objects deleted */
const lv_fragment_class_t * cls = fragment->cls;
if(cls->destructor_cb) {
cls->destructor_cb(fragment);
}
lv_fragment_manager_delete(fragment->child_manager);
lv_free(fragment);
}
lv_fragment_manager_t * lv_fragment_get_manager(lv_fragment_t * fragment)
{
LV_ASSERT_NULL(fragment);
LV_ASSERT_NULL(fragment->managed);
return fragment->managed->manager;
}
lv_obj_t * const * lv_fragment_get_container(lv_fragment_t * fragment)
{
LV_ASSERT_NULL(fragment);
LV_ASSERT_NULL(fragment->managed);
return fragment->managed->container;
}
lv_fragment_t * lv_fragment_get_parent(lv_fragment_t * fragment)
{
LV_ASSERT_NULL(fragment);
LV_ASSERT_NULL(fragment->managed);
return lv_fragment_manager_get_parent_fragment(fragment->managed->manager);
}
lv_obj_t * lv_fragment_create_obj(lv_fragment_t * fragment, lv_obj_t * container)
{
lv_fragment_managed_states_t * states = fragment->managed;
if(states) {
states->destroying_obj = false;
}
const lv_fragment_class_t * cls = fragment->cls;
lv_obj_t * obj = cls->create_obj_cb(fragment, container);
LV_ASSERT_NULL(obj);
fragment->obj = obj;
lv_fragment_manager_create_obj(fragment->child_manager);
if(states) {
states->obj_created = true;
lv_obj_add_event(obj, cb_delete_assertion, LV_EVENT_DELETE, NULL);
}
if(cls->obj_created_cb) {
cls->obj_created_cb(fragment, obj);
}
return obj;
}
void lv_fragment_delete_obj(lv_fragment_t * fragment)
{
LV_ASSERT_NULL(fragment);
lv_fragment_manager_delete_obj(fragment->child_manager);
lv_fragment_managed_states_t * states = fragment->managed;
if(states) {
if(!states->obj_created) return;
states->destroying_obj = true;
uint32_t i;
uint32_t event_cnt = lv_obj_get_event_count(fragment->obj);
bool cb_removed = false;
for(i = 0; i < event_cnt; i++) {
lv_event_dsc_t * event_dsc = lv_obj_get_event_dsc(fragment->obj, i);
if(lv_event_dsc_get_cb(event_dsc) == cb_delete_assertion) {
cb_removed = lv_obj_remove_event(fragment->obj, i);
break;
}
}
LV_ASSERT(cb_removed);
}
LV_ASSERT_NULL(fragment->obj);
const lv_fragment_class_t * cls = fragment->cls;
if(cls->obj_will_delete_cb) {
cls->obj_will_delete_cb(fragment, fragment->obj);
}
lv_obj_delete(fragment->obj);
if(cls->obj_deleted_cb) {
cls->obj_deleted_cb(fragment, fragment->obj);
}
if(states) {
states->obj_created = false;
}
fragment->obj = NULL;
}
void lv_fragment_recreate_obj(lv_fragment_t * fragment)
{
LV_ASSERT_NULL(fragment);
LV_ASSERT_NULL(fragment->managed);
lv_fragment_delete_obj(fragment);
lv_fragment_create_obj(fragment, *fragment->managed->container);
}
/**********************
* STATIC FUNCTIONS
**********************/
static void cb_delete_assertion(lv_event_t * event)
{
LV_UNUSED(event);
LV_ASSERT_MSG(0, "Please delete objects with lv_fragment_destroy_obj");
}
#endif /*LV_USE_FRAGMENT*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/fragment/lv_fragment.h | /**
* Public header for Fragment
* @file lv_fragment.h
*/
#ifndef LV_FRAGMENT_H
#define LV_FRAGMENT_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../core/lv_obj.h"
#if LV_USE_FRAGMENT
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct _lv_fragment_manager_t lv_fragment_manager_t;
typedef struct _lv_fragment_t lv_fragment_t;
typedef struct _lv_fragment_class_t lv_fragment_class_t;
typedef struct _lv_fragment_managed_states_t lv_fragment_managed_states_t;
struct _lv_fragment_t {
/**
* Class of this fragment
*/
const lv_fragment_class_t * cls;
/**
* Managed fragment states. If not null, then this fragment is managed.
*
* @warning Don't modify values inside this struct!
*/
lv_fragment_managed_states_t * managed;
/**
* Child fragment manager
*/
lv_fragment_manager_t * child_manager;
/**
* lv_obj returned by create_obj_cb
*/
lv_obj_t * obj;
};
struct _lv_fragment_class_t {
/**
* Constructor function for fragment class
* @param self Fragment instance
* @param args Arguments assigned by fragment manager
*/
void (*constructor_cb)(lv_fragment_t * self, void * args);
/**
* Destructor function for fragment class
* @param self Fragment instance, will be freed after this call
*/
void (*destructor_cb)(lv_fragment_t * self);
/**
* Fragment attached to manager
* @param self Fragment instance
*/
void (*attached_cb)(lv_fragment_t * self);
/**
* Fragment detached from manager
* @param self Fragment instance
*/
void (*detached_cb)(lv_fragment_t * self);
/**
* Create objects
* @param self Fragment instance
* @param container Container of the objects should be created upon
* @return Created object, NULL if multiple objects has been created
*/
lv_obj_t * (*create_obj_cb)(lv_fragment_t * self, lv_obj_t * container);
/**
*
* @param self Fragment instance
* @param obj lv_obj returned by create_obj_cb
*/
void (*obj_created_cb)(lv_fragment_t * self, lv_obj_t * obj);
/**
* Called before objects in the fragment will be deleted.
*
* @param self Fragment instance
* @param obj object with this fragment
*/
void (*obj_will_delete_cb)(lv_fragment_t * self, lv_obj_t * obj);
/**
* Called when the object created by fragment received `LV_EVENT_DELETE` event
* @param self Fragment instance
* @param obj object with this fragment
*/
void (*obj_deleted_cb)(lv_fragment_t * self, lv_obj_t * obj);
/**
* Handle event
* @param self Fragment instance
* @param which User-defined ID of event
* @param data1 User-defined data
* @param data2 User-defined data
*/
bool (*event_cb)(lv_fragment_t * self, int code, void * userdata);
/**
* *REQUIRED*: Allocation size of fragment
*/
size_t instance_size;
};
/**
* Fragment states
*/
typedef struct _lv_fragment_managed_states_t {
/**
* Class of the fragment
*/
const lv_fragment_class_t * cls;
/**
* Manager the fragment attached to
*/
lv_fragment_manager_t * manager;
/**
* Container object the fragment adding view to
*/
lv_obj_t * const * container;
/**
* Fragment instance
*/
lv_fragment_t * instance;
/**
* true between `create_obj_cb` and `obj_deleted_cb`
*/
bool obj_created;
/**
* true before `lv_fragment_delete_obj` is called. Don't touch any object if this is true
*/
bool destroying_obj;
/**
* true if this fragment is in navigation stack that can be popped
*/
bool in_stack;
} lv_fragment_managed_states_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create fragment manager instance
* @param parent Parent fragment if this manager is placed inside another fragment, can be null.
* @return Fragment manager instance
*/
lv_fragment_manager_t * lv_fragment_manager_create(lv_fragment_t * parent);
/**
* Destroy fragment manager instance
* @param manager Fragment manager instance
*/
void lv_fragment_manager_delete(lv_fragment_manager_t * manager);
/**
* Create object of all fragments managed by this manager.
* @param manager Fragment manager instance
*/
void lv_fragment_manager_create_obj(lv_fragment_manager_t * manager);
/**
* Delete object created by all fragments managed by this manager. Instance of fragments will not be deleted.
* @param manager Fragment manager instance
*/
void lv_fragment_manager_delete_obj(lv_fragment_manager_t * manager);
/**
* Attach fragment to manager, and add to container.
* @param manager Fragment manager instance
* @param fragment Fragment instance
* @param container Pointer to container object for manager to add objects to
*/
void lv_fragment_manager_add(lv_fragment_manager_t * manager, lv_fragment_t * fragment, lv_obj_t * const * container);
/**
* Detach and destroy fragment. If fragment is in navigation stack, remove from it.
* @param manager Fragment manager instance
* @param fragment Fragment instance
*/
void lv_fragment_manager_remove(lv_fragment_manager_t * manager, lv_fragment_t * fragment);
/**
* Attach fragment to manager and add to navigation stack.
* @param manager Fragment manager instance
* @param fragment Fragment instance
* @param container Pointer to container object for manager to add objects to
*/
void lv_fragment_manager_push(lv_fragment_manager_t * manager, lv_fragment_t * fragment, lv_obj_t * const * container);
/**
* Remove the top-most fragment for stack
* @param manager Fragment manager instance
* @return true if there is fragment to pop
*/
bool lv_fragment_manager_pop(lv_fragment_manager_t * manager);
/**
* Replace fragment. Old item in the stack will be removed.
* @param manager Fragment manager instance
* @param fragment Fragment instance
* @param container Pointer to container object for manager to add objects to
*/
void lv_fragment_manager_replace(lv_fragment_manager_t * manager, lv_fragment_t * fragment,
lv_obj_t * const * container);
/**
* Send event to top-most fragment
* @param manager Fragment manager instance
* @param code User-defined ID of event
* @param userdata User-defined data
* @return true if fragment returned true
*/
bool lv_fragment_manager_send_event(lv_fragment_manager_t * manager, int code, void * userdata);
/**
* Get stack size of this fragment manager
* @param manager Fragment manager instance
* @return Stack size of this fragment manager
*/
size_t lv_fragment_manager_get_stack_size(lv_fragment_manager_t * manager);
/**
* Get top most fragment instance
* @param manager Fragment manager instance
* @return Top most fragment instance
*/
lv_fragment_t * lv_fragment_manager_get_top(lv_fragment_manager_t * manager);
/**
* Find first fragment instance in the container
* @param manager Fragment manager instance
* @param container Container which target fragment added to
* @return First fragment instance in the container
*/
lv_fragment_t * lv_fragment_manager_find_by_container(lv_fragment_manager_t * manager, const lv_obj_t * container);
/**
* Get parent fragment
* @param manager Fragment manager instance
* @return Parent fragment instance
*/
lv_fragment_t * lv_fragment_manager_get_parent_fragment(lv_fragment_manager_t * manager);
/**
* Create a fragment instance.
*
* @param cls Fragment class. This fragment must return non null object.
* @param args Arguments assigned by fragment manager
* @return Fragment instance
*/
lv_fragment_t * lv_fragment_create(const lv_fragment_class_t * cls, void * args);
/**
* Destroy a fragment.
* @param fragment Fragment instance.
*/
void lv_fragment_delete(lv_fragment_t * fragment);
/**
* Get associated manager of this fragment
* @param fragment Fragment instance
* @return Fragment manager instance
*/
lv_fragment_manager_t * lv_fragment_get_manager(lv_fragment_t * fragment);
/**
* Get container object of this fragment
* @param fragment Fragment instance
* @return Reference to container object
*/
lv_obj_t * const * lv_fragment_get_container(lv_fragment_t * fragment);
/**
* Get parent fragment of this fragment
* @param fragment Fragment instance
* @return Parent fragment
*/
lv_fragment_t * lv_fragment_get_parent(lv_fragment_t * fragment);
/**
* Create object by fragment.
*
* @param fragment Fragment instance.
* @param container Container of the objects should be created upon.
* @return Created object
*/
lv_obj_t * lv_fragment_create_obj(lv_fragment_t * fragment, lv_obj_t * container);
/**
* Delete created object of a fragment
*
* @param fragment Fragment instance.
*/
void lv_fragment_delete_obj(lv_fragment_t * fragment);
/**
* Destroy obj in fragment, and recreate them.
* @param fragment Fragment instance
*/
void lv_fragment_recreate_obj(lv_fragment_t * fragment);
/**********************
* MACROS
**********************/
#endif /*LV_USE_FRAGMENT*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_FRAGMENT_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/fragment/lv_fragment_manager.c | /**
* @file lv_fragment_manager.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_fragment.h"
#if LV_USE_FRAGMENT
#include "../../misc/lv_ll.h"
#include "../../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct _lv_fragment_stack_item_t {
lv_fragment_managed_states_t * states;
} lv_fragment_stack_item_t;
struct _lv_fragment_manager_t {
lv_fragment_t * parent;
/**
* Linked list to store attached fragments
*/
lv_ll_t attached;
/**
* Linked list to store fragments in stack
*/
lv_ll_t stack;
};
/**********************
* STATIC PROTOTYPES
**********************/
static void item_create_obj(lv_fragment_managed_states_t * item);
static void item_delete_obj(lv_fragment_managed_states_t * item);
static void item_delete_fragment(lv_fragment_managed_states_t * item);
static lv_fragment_managed_states_t * fragment_attach(lv_fragment_manager_t * manager, lv_fragment_t * fragment,
lv_obj_t * const * container);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_fragment_manager_t * lv_fragment_manager_create(lv_fragment_t * parent)
{
lv_fragment_manager_t * instance = lv_malloc(sizeof(lv_fragment_manager_t));
lv_memzero(instance, sizeof(lv_fragment_manager_t));
instance->parent = parent;
_lv_ll_init(&instance->attached, sizeof(lv_fragment_managed_states_t));
_lv_ll_init(&instance->stack, sizeof(lv_fragment_stack_item_t));
return instance;
}
void lv_fragment_manager_delete(lv_fragment_manager_t * manager)
{
LV_ASSERT_NULL(manager);
lv_fragment_managed_states_t * states;
_LV_LL_READ_BACK(&manager->attached, states) {
item_delete_obj(states);
item_delete_fragment(states);
}
_lv_ll_clear(&manager->attached);
_lv_ll_clear(&manager->stack);
lv_free(manager);
}
void lv_fragment_manager_create_obj(lv_fragment_manager_t * manager)
{
LV_ASSERT_NULL(manager);
lv_fragment_stack_item_t * top = _lv_ll_get_tail(&manager->stack);
lv_fragment_managed_states_t * states = NULL;
_LV_LL_READ(&manager->attached, states) {
if(states->in_stack && top->states != states) {
/*Only create obj for top item in stack*/
continue;
}
item_create_obj(states);
}
}
void lv_fragment_manager_delete_obj(lv_fragment_manager_t * manager)
{
LV_ASSERT_NULL(manager);
lv_fragment_managed_states_t * states = NULL;
_LV_LL_READ_BACK(&manager->attached, states) {
item_delete_obj(states);
}
}
void lv_fragment_manager_add(lv_fragment_manager_t * manager, lv_fragment_t * fragment, lv_obj_t * const * container)
{
lv_fragment_managed_states_t * states = fragment_attach(manager, fragment, container);
if(!manager->parent || manager->parent->managed->obj_created) {
item_create_obj(states);
}
}
void lv_fragment_manager_remove(lv_fragment_manager_t * manager, lv_fragment_t * fragment)
{
LV_ASSERT_NULL(manager);
LV_ASSERT_NULL(fragment);
LV_ASSERT_NULL(fragment->managed);
LV_ASSERT(fragment->managed->manager == manager);
lv_fragment_managed_states_t * states = fragment->managed;
lv_fragment_managed_states_t * prev = NULL;
bool was_top = false;
if(states->in_stack) {
void * stack_top = _lv_ll_get_tail(&manager->stack);
lv_fragment_stack_item_t * item = NULL;
_LV_LL_READ_BACK(&manager->stack, item) {
if(item->states == states) {
was_top = stack_top == item;
void * stack_prev = _lv_ll_get_prev(&manager->stack, item);
if(!stack_prev) break;
prev = ((lv_fragment_stack_item_t *) stack_prev)->states;
break;
}
}
if(item) {
_lv_ll_remove(&manager->stack, item);
lv_free(item);
}
}
item_delete_obj(states);
item_delete_fragment(states);
_lv_ll_remove(&manager->attached, states);
lv_free(states);
if(prev && was_top) {
item_create_obj(prev);
}
}
void lv_fragment_manager_push(lv_fragment_manager_t * manager, lv_fragment_t * fragment, lv_obj_t * const * container)
{
lv_fragment_stack_item_t * top = _lv_ll_get_tail(&manager->stack);
if(top != NULL) {
item_delete_obj(top->states);
}
lv_fragment_managed_states_t * states = fragment_attach(manager, fragment, container);
states->in_stack = true;
/*Add fragment to the top of the stack*/
lv_fragment_stack_item_t * item = _lv_ll_ins_tail(&manager->stack);
lv_memzero(item, sizeof(lv_fragment_stack_item_t));
item->states = states;
item_create_obj(states);
}
bool lv_fragment_manager_pop(lv_fragment_manager_t * manager)
{
lv_fragment_t * top = lv_fragment_manager_get_top(manager);
if(top == NULL) return false;
lv_fragment_manager_remove(manager, top);
return true;
}
void lv_fragment_manager_replace(lv_fragment_manager_t * manager, lv_fragment_t * fragment,
lv_obj_t * const * container)
{
lv_fragment_t * top = lv_fragment_manager_find_by_container(manager, *container);
if(top != NULL) {
lv_fragment_manager_remove(manager, top);
}
lv_fragment_manager_add(manager, fragment, container);
}
bool lv_fragment_manager_send_event(lv_fragment_manager_t * manager, int code, void * userdata)
{
LV_ASSERT_NULL(manager);
lv_fragment_managed_states_t * p = NULL;
_LV_LL_READ_BACK(&manager->attached, p) {
if(!p->obj_created || p->destroying_obj) continue;
lv_fragment_t * instance = p->instance;
if(!instance) continue;
if(lv_fragment_manager_send_event(instance->child_manager, code, userdata)) return true;
if(p->cls->event_cb && p->cls->event_cb(instance, code, userdata)) return true;
}
return false;
}
size_t lv_fragment_manager_get_stack_size(lv_fragment_manager_t * manager)
{
LV_ASSERT_NULL(manager);
return _lv_ll_get_len(&manager->stack);
}
lv_fragment_t * lv_fragment_manager_get_top(lv_fragment_manager_t * manager)
{
LV_ASSERT(manager);
lv_fragment_stack_item_t * top = _lv_ll_get_tail(&manager->stack);
if(!top)return NULL;
return top->states->instance;
}
lv_fragment_t * lv_fragment_manager_find_by_container(lv_fragment_manager_t * manager, const lv_obj_t * container)
{
LV_ASSERT(manager);
lv_fragment_managed_states_t * states;
_LV_LL_READ(&manager->attached, states) {
if(*states->container == container) return states->instance;
}
return NULL;
}
lv_fragment_t * lv_fragment_manager_get_parent_fragment(lv_fragment_manager_t * manager)
{
LV_ASSERT_NULL(manager);
return manager->parent;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void item_create_obj(lv_fragment_managed_states_t * item)
{
LV_ASSERT(item->instance);
lv_fragment_create_obj(item->instance, item->container ? *item->container : NULL);
}
static void item_delete_obj(lv_fragment_managed_states_t * item)
{
lv_fragment_delete_obj(item->instance);
}
/**
* Detach, then destroy fragment
* @param item fragment states
*/
static void item_delete_fragment(lv_fragment_managed_states_t * item)
{
lv_fragment_t * instance = item->instance;
if(instance->cls->detached_cb) {
instance->cls->detached_cb(instance);
}
instance->managed = NULL;
lv_fragment_delete(instance);
item->instance = NULL;
}
static lv_fragment_managed_states_t * fragment_attach(lv_fragment_manager_t * manager, lv_fragment_t * fragment,
lv_obj_t * const * container)
{
LV_ASSERT(manager);
LV_ASSERT(fragment);
LV_ASSERT(fragment->managed == NULL);
lv_fragment_managed_states_t * states = _lv_ll_ins_tail(&manager->attached);
lv_memzero(states, sizeof(lv_fragment_managed_states_t));
states->cls = fragment->cls;
states->manager = manager;
states->container = container;
states->instance = fragment;
fragment->managed = states;
if(fragment->cls->attached_cb) {
fragment->cls->attached_cb(fragment);
}
return states;
}
#endif /*LV_USE_FRAGMENT*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/snapshot/lv_snapshot.h | /**
* @file lv_snapshot.h
*
*/
#ifndef LV_SNAPSHOT_H
#define LV_SNAPSHOT_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include <stdint.h>
#include <stddef.h>
#include "../../core/lv_obj.h"
/*********************
* DEFINES
*********************/
#if LV_USE_SNAPSHOT
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Take snapshot for object with its children, alloc the memory needed.
* @param obj the object to generate snapshot.
* @param cf color format for generated image.
* @return a pointer to an image descriptor, or NULL if failed.
*/
lv_image_dsc_t * lv_snapshot_take(lv_obj_t * obj, lv_color_format_t cf);
/**
* Free the snapshot image returned by @ref lv_snapshot_take
* It will firstly free the data image takes, then the image descriptor.
* @param dsc the image descriptor generated by lv_snapshot_take.
*/
void lv_snapshot_free(lv_image_dsc_t * dsc);
/**
* Get the buffer needed for object snapshot image.
* @param obj the object to generate snapshot.
* @param cf color format for generated image.
* @return the buffer size needed in bytes
*/
uint32_t lv_snapshot_buf_size_needed(lv_obj_t * obj, lv_color_format_t cf);
/**
* Take snapshot for object with its children, save image info to provided buffer.
* @param obj the object to generate snapshot.
* @param cf color format for generated image.
* @param dsc image descriptor to store the image result.
* @param buf the buffer to store image data.
* @param buff_size provided buffer size in bytes.
* @return LV_RESULT_OK on success, LV_RESULT_INVALID on error.
*/
lv_result_t lv_snapshot_take_to_buf(lv_obj_t * obj, lv_color_format_t cf, lv_image_dsc_t * dsc, void * buf,
uint32_t buff_size);
/**********************
* MACROS
**********************/
#endif /*LV_USE_SNAPSHOT*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/snapshot/lv_snapshot.c | /**
* @file lv_snapshot.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_snapshot.h"
#if LV_USE_SNAPSHOT
#include <stdbool.h>
#include "../../display/lv_display.h"
#include "../../core/lv_refr.h"
#include "../../display/lv_display_private.h"
#include "../../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Get the buffer needed for object snapshot image.
* @param obj the object to generate snapshot.
* @param cf color format for generated image.
* @return the buffer size needed in bytes
*/
uint32_t lv_snapshot_buf_size_needed(lv_obj_t * obj, lv_color_format_t cf)
{
LV_ASSERT_NULL(obj);
switch(cf) {
case LV_COLOR_FORMAT_RGB565:
case LV_COLOR_FORMAT_RGB888:
case LV_COLOR_FORMAT_XRGB8888:
case LV_COLOR_FORMAT_ARGB8888:
break;
default:
LV_LOG_WARN("Not supported color format");
return 0;
}
lv_obj_update_layout(obj);
/*Width and height determine snapshot image size.*/
int32_t w = lv_obj_get_width(obj);
int32_t h = lv_obj_get_height(obj);
int32_t ext_size = _lv_obj_get_ext_draw_size(obj);
w += ext_size * 2;
h += ext_size * 2;
return lv_draw_buf_width_to_stride(w, cf) * h;
}
/**
* Take snapshot for object with its children, save image info to provided buffer.
* @param obj the object to generate snapshot.
* @param cf color format for generated image.
* @param dsc image descriptor to store the image result.
* @param buf the buffer to store image data.
* @param buff_size provided buffer size in bytes.
* @return LV_RESULT_OK on success, LV_RESULT_INVALID on error.
*/
lv_result_t lv_snapshot_take_to_buf(lv_obj_t * obj, lv_color_format_t cf, lv_image_dsc_t * dsc, void * buf,
uint32_t buff_size)
{
LV_ASSERT_NULL(obj);
LV_ASSERT_NULL(dsc);
LV_ASSERT_NULL(buf);
switch(cf) {
case LV_COLOR_FORMAT_RGB565:
case LV_COLOR_FORMAT_RGB888:
case LV_COLOR_FORMAT_XRGB8888:
case LV_COLOR_FORMAT_ARGB8888:
break;
default:
LV_LOG_WARN("Not supported color format");
return LV_RESULT_INVALID;
}
if(lv_snapshot_buf_size_needed(obj, cf) > buff_size || buff_size == 0) return LV_RESULT_INVALID;
/*Width and height determine snapshot image size.*/
int32_t w = lv_obj_get_width(obj);
int32_t h = lv_obj_get_height(obj);
int32_t ext_size = _lv_obj_get_ext_draw_size(obj);
w += ext_size * 2;
h += ext_size * 2;
lv_area_t snapshot_area;
lv_obj_get_coords(obj, &snapshot_area);
lv_area_increase(&snapshot_area, ext_size, ext_size);
lv_memzero(buf, buff_size);
lv_memzero(dsc, sizeof(lv_image_dsc_t));
dsc->data = buf;
dsc->header.w = w;
dsc->header.h = h;
dsc->header.cf = cf;
dsc->header.always_zero = 0;
lv_layer_t layer;
lv_memzero(&layer, sizeof(layer));
layer.buf = lv_draw_buf_align(buf, cf);
layer.buf_area.x1 = snapshot_area.x1;
layer.buf_area.y1 = snapshot_area.y1;
layer.buf_area.x2 = snapshot_area.x1 + w - 1;
layer.buf_area.y2 = snapshot_area.y1 + h - 1;
layer.color_format = cf;
layer.clip_area = snapshot_area;
lv_obj_redraw(&layer, obj);
while(layer.draw_task_head) {
lv_draw_dispatch_wait_for_request();
lv_draw_dispatch_layer(NULL, &layer);
}
return LV_RESULT_OK;
}
/**
* Take snapshot for object with its children, alloc the memory needed.
* @param obj the object to generate snapshot.
* @param cf color format for generated image.
* @return a pointer to an image descriptor, or NULL if failed.
*/
lv_image_dsc_t * lv_snapshot_take(lv_obj_t * obj, lv_color_format_t cf)
{
LV_ASSERT_NULL(obj);
uint32_t buff_size = lv_snapshot_buf_size_needed(obj, cf);
if(buff_size == 0) return NULL;
void * buf = lv_malloc(buff_size);
LV_ASSERT_MALLOC(buf);
if(buf == NULL) {
return NULL;
}
lv_image_dsc_t * dsc = lv_malloc(sizeof(lv_image_dsc_t));
LV_ASSERT_MALLOC(buf);
if(dsc == NULL) {
lv_free(buf);
return NULL;
}
if(lv_snapshot_take_to_buf(obj, cf, dsc, buf, buff_size) == LV_RESULT_INVALID) {
lv_free(buf);
lv_free(dsc);
return NULL;
}
return dsc;
}
/**
* Free the snapshot image returned by @ref lv_snapshot_take
* It will firstly free the data image takes, then the image descriptor.
* @param dsc the image descriptor generated by lv_snapshot_take.
*/
void lv_snapshot_free(lv_image_dsc_t * dsc)
{
if(!dsc)
return;
if(dsc->data)
lv_free((void *)dsc->data);
lv_free(dsc);
}
/**********************
* STATIC FUNCTIONS
**********************/
#endif /*LV_USE_SNAPSHOT*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/ime/lv_ime_pinyin.c | /**
* @file lv_ime_pinyin.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_ime_pinyin.h"
#if LV_USE_IME_PINYIN != 0
#include <stdio.h>
#include "../../core/lv_global.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_ime_pinyin_class
#define cand_len LV_GLOBAL_DEFAULT()->ime_cand_len
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_ime_pinyin_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_ime_pinyin_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_ime_pinyin_style_change_event(lv_event_t * e);
static void lv_ime_pinyin_kb_event(lv_event_t * e);
static void lv_ime_pinyin_cand_panel_event(lv_event_t * e);
static void init_pinyin_dict(lv_obj_t * obj, const lv_pinyin_dict_t * dict);
static void pinyin_input_proc(lv_obj_t * obj);
static void pinyin_page_proc(lv_obj_t * obj, uint16_t btn);
static char * pinyin_search_matching(lv_obj_t * obj, char * py_str, uint16_t * cand_num);
static void pinyin_ime_clear_data(lv_obj_t * obj);
#if LV_IME_PINYIN_USE_K9_MODE
static void pinyin_k9_init_data(lv_obj_t * obj);
static void pinyin_k9_get_legal_py(lv_obj_t * obj, char * k9_input, const char * py9_map[]);
static bool pinyin_k9_is_valid_py(lv_obj_t * obj, char * py_str);
static void pinyin_k9_fill_cand(lv_obj_t * obj);
static void pinyin_k9_cand_page_proc(lv_obj_t * obj, uint16_t dir);
#endif
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_ime_pinyin_class = {
.constructor_cb = lv_ime_pinyin_constructor,
.destructor_cb = lv_ime_pinyin_destructor,
.width_def = LV_SIZE_CONTENT,
.height_def = LV_SIZE_CONTENT,
.group_def = LV_OBJ_CLASS_GROUP_DEF_TRUE,
.instance_size = sizeof(lv_ime_pinyin_t),
.base_class = &lv_obj_class,
.name = "ime-pinyin",
};
#if LV_IME_PINYIN_USE_K9_MODE
static const char * lv_btnm_def_pinyin_k9_map[LV_IME_PINYIN_K9_CAND_TEXT_NUM + 21] = {\
",\0", "123\0", "abc \0", "def\0", LV_SYMBOL_BACKSPACE"\0", "\n\0",
".\0", "ghi\0", "jkl\0", "mno\0", LV_SYMBOL_KEYBOARD"\0", "\n\0",
"?\0", "pqrs\0", "tuv\0", "wxyz\0", LV_SYMBOL_NEW_LINE"\0", "\n\0",
LV_SYMBOL_LEFT"\0", "\0"
};
static lv_buttonmatrix_ctrl_t default_kb_ctrl_k9_map[LV_IME_PINYIN_K9_CAND_TEXT_NUM + 17] = { 1 };
static char lv_pinyin_k9_cand_str[LV_IME_PINYIN_K9_CAND_TEXT_NUM + 2][LV_IME_PINYIN_K9_MAX_INPUT] = {0};
#endif
static char lv_pinyin_cand_str[LV_IME_PINYIN_CAND_TEXT_NUM][4];
static char * lv_btnm_def_pinyin_sel_map[LV_IME_PINYIN_CAND_TEXT_NUM + 3];
#if LV_IME_PINYIN_USE_DEFAULT_DICT
static const lv_pinyin_dict_t lv_ime_pinyin_def_dict[] = {
{ "a", "啊" },
{ "ai", "愛" },
{ "an", "安暗案" },
{ "ba", "吧把爸八" },
{ "bai", "百白敗" },
{ "ban", "半般辦" },
{ "bang", "旁" },
{ "bao", "保薄包報" },
{ "bei", "被背悲北杯備" },
{ "ben", "本" },
{ "bi", "必比避鼻彼筆秘閉" },
{ "bian", "便邊變変辺" },
{ "biao", "表標" },
{ "bie", "別" },
{ "bing", "病並氷" },
{ "bo", "波薄泊" },
{ "bu", "不布步部捕補歩" },
{ "ca", "察" },
{ "cai", "才材菜財採" },
{ "can", "参残參" },
{ "ce", "策側" },
{ "ceng", "曾" },
{ "cha", "差查茶" },
{ "chai", "差" },
{ "chan", "產産單" },
{ "chang", "場廠" },
{ "chao", "超朝" },
{ "che", "車" },
{ "cheng", "成程乗" },
{ "chi", "尺吃持赤池遅歯" },
{ "chong", "充种重種" },
{ "chu", "出初楚触處処" },
{ "chuan", "川船傳" },
{ "chuang", "創窓" },
{ "chun", "春" },
{ "ci", "此次辞差" },
{ "cong", "從従" },
{ "cu", "卒" },
{ "cun", "存村" },
{ "cuo", "錯" },
{ "da", "大打答達" },
{ "dai", "代待帯帶貸" },
{ "dan", "但担擔誕單単" },
{ "dang", "当党當黨" },
{ "dao", "到道盗導島辺" },
{ "de", "的得" },
{ "dei", "" },
{ "deng", "等" },
{ "di", "地得低底弟第締" },
{ "dian", "点电店點電" },
{ "diao", "調" },
{ "ding", "定町" },
{ "dong", "冬東動働凍" },
{ "du", "独度都渡読" },
{ "duan", "段断短斷" },
{ "dui", "對対" },
{ "duo", "多駄" },
{ "e", "嗯悪" },
{ "en", "嗯" },
{ "er", "而耳二兒" },
{ "fa", "乏法發発髪" },
{ "fan", "反返犯番仮販飯範払" },
{ "fang", "方放房坊訪" },
{ "fei", "非飛費" },
{ "fen", "分份" },
{ "feng", "風豐" },
{ "fou", "否不" },
{ "fu", "父夫富服符付附府幅婦復複負払" },
{ "gai", "改概該" },
{ "gan", "甘感敢" },
{ "gang", "港剛" },
{ "gao", "告高" },
{ "ge", "各格歌革割個" },
{ "gei", "給" },
{ "gen", "跟根" },
{ "geng", "更" },
{ "gong", "工共供功公" },
{ "gou", "夠構溝" },
{ "gu", "古故鼓" },
{ "guai", "掛" },
{ "guan", "官管慣館觀関關" },
{ "guang", "光広" },
{ "gui", "規帰" },
{ "guo", "果国裏菓國過" },
{ "hai", "孩海害還" },
{ "han", "寒漢" },
{ "hang", "航行" },
{ "hao", "好号" },
{ "he", "合和喝何荷" },
{ "hei", "黒" },
{ "hen", "很" },
{ "heng", "行横" },
{ "hou", "厚喉候後" },
{ "hu", "乎呼湖護" },
{ "hua", "化画花話畫劃" },
{ "huai", "壊劃" },
{ "huan", "緩環歡還換" },
{ "huang", "黄" },
{ "hui", "回会慧絵揮會" },
{ "hun", "混婚" },
{ "huo", "活或火獲" },
{ "i", "" },
{ "ji", "己计及机既急季寄技即集基祭系奇紀積計記済幾際極繼績機濟" },
{ "jia", "家加價" },
{ "jian", "件建健肩見減間検簡漸" },
{ "jiang", "降強講將港" },
{ "jiao", "叫教交角覚覺較學" },
{ "jie", "介借接姐皆届界解結階節價" },
{ "jin", "今近禁金僅進" },
{ "jing", "京境景静精經経" },
{ "jiu", "就久九酒究" },
{ "ju", "句具局居決挙據舉" },
{ "jue", "角覚覺" },
{ "jun", "均" },
{ "kai", "開" },
{ "kan", "看刊" },
{ "kang", "康" },
{ "kao", "考" },
{ "ke", "可刻科克客渇課" },
{ "ken", "肯" },
{ "kong", "空控" },
{ "kou", "口" },
{ "ku", "苦庫" },
{ "kuai", "快塊会會" },
{ "kuang", "況" },
{ "kun", "困" },
{ "kuo", "括拡適" },
{ "la", "拉啦落" },
{ "lai", "来來頼" },
{ "lao", "老絡落" },
{ "le", "了楽樂" },
{ "lei", "類" },
{ "leng", "冷" },
{ "li", "力立利理例礼離麗裡勵歷" },
{ "lian", "連練臉聯" },
{ "liang", "良量涼兩両" },
{ "liao", "料" },
{ "lie", "列" },
{ "lin", "林隣賃" },
{ "ling", "另令領" },
{ "liu", "六留流" },
{ "lu", "律路録緑陸履慮" },
{ "lv", "旅" },
{ "lun", "輪論" },
{ "luo", "落絡" },
{ "ma", "媽嗎嘛" },
{ "mai", "買売" },
{ "man", "滿" },
{ "mang", "忙" },
{ "mao", "毛猫貿" },
{ "me", "麼" },
{ "mei", "美妹每沒毎媒" },
{ "men", "們" },
{ "mi", "米密秘" },
{ "mian", "免面勉眠" },
{ "miao", "描" },
{ "min", "民皿" },
{ "ming", "命明名" },
{ "mo", "末模麼" },
{ "mou", "某" },
{ "mu", "母木目模" },
{ "na", "那哪拿內南" },
{ "nan", "男南難" },
{ "nao", "腦" },
{ "ne", "那哪呢" },
{ "nei", "内那哪內" },
{ "neng", "能" },
{ "ni", "你妳呢" },
{ "nian", "年念" },
{ "niang", "娘" },
{ "nin", "您" },
{ "ning", "凝" },
{ "niu", "牛" },
{ "nong", "農濃" },
{ "nu", "女努" },
{ "nuan", "暖" },
{ "o", "" },
{ "ou", "歐" },
{ "pa", "怕" },
{ "pai", "迫派排" },
{ "pan", "判番" },
{ "pang", "旁" },
{ "pei", "配" },
{ "peng", "朋" },
{ "pi", "疲否" },
{ "pian", "片便" },
{ "pin", "品貧" },
{ "ping", "平評" },
{ "po", "迫破泊頗" },
{ "pu", "普僕" },
{ "qi", "起其奇七气期泣企妻契気" },
{ "qian", "嵌浅千前鉛錢針" },
{ "qiang", "強將" },
{ "qiao", "橋繰" },
{ "qie", "且切契" },
{ "qin", "寝勤親" },
{ "qing", "青清情晴輕頃請軽" },
{ "qiu", "求秋球" },
{ "qu", "去取趣曲區" },
{ "quan", "全犬券" },
{ "que", "缺確卻" },
{ "ran", "然" },
{ "rang", "讓" },
{ "re", "熱" },
{ "ren", "人任認" },
{ "reng", "仍" },
{ "ri", "日" },
{ "rong", "容" },
{ "rou", "弱若肉" },
{ "ru", "如入" },
{ "ruan", "軟" },
{ "sai", "賽" },
{ "san", "三" },
{ "sao", "騒繰" },
{ "se", "色" },
{ "sen", "森" },
{ "sha", "砂" },
{ "shan", "善山單" },
{ "shang", "上尚商" },
{ "shao", "少紹" },
{ "shaung", "雙" },
{ "she", "社射設捨渉" },
{ "shei", "誰" },
{ "shen", "什申深甚身伸沈神" },
{ "sheng", "生声昇勝乗聲" },
{ "shi", "是失示食时事式十石施使世实史室市始柿氏士仕拭時視師試適実實識" },
{ "shou", "手首守受授" },
{ "shu", "束数暑殊樹書屬輸術" },
{ "shui", "水説說誰" },
{ "shuo", "数説說" },
{ "si", "思寺司四私似死価" },
{ "song", "送" },
{ "su", "速宿素蘇訴" },
{ "suan", "算酸" },
{ "sui", "隨雖歲歳" },
{ "sun", "孫" },
{ "suo", "所" },
{ "ta", "她他它牠" },
{ "tai", "太台態臺" },
{ "tan", "探談曇" },
{ "tang", "糖" },
{ "tao", "桃逃套討" },
{ "te", "特" },
{ "ti", "体提替題體戻" },
{ "tian", "天田" },
{ "tiao", "条條調" },
{ "tie", "鉄" },
{ "ting", "停庭聽町" },
{ "tong", "同童通痛统統" },
{ "tou", "投透頭" },
{ "tu", "土徒茶図" },
{ "tuan", "團" },
{ "tui", "推退" },
{ "tuo", "脱駄" },
{ "u", "" },
{ "v", "" },
{ "wai", "外" },
{ "wan", "完万玩晩腕灣" },
{ "wang", "忘望亡往網" },
{ "wei", "危位未味委為謂維違圍" },
{ "wen", "文温問聞" },
{ "wo", "我" },
{ "wu", "午物五無屋亡鳥務汚" },
{ "xi", "夕息西洗喜系昔席希析嬉膝細習係" },
{ "xia", "下夏狭暇" },
{ "xian", "先限嫌洗現見線顯" },
{ "xiang", "向相香像想象降項詳響" },
{ "xiao", "小笑消效校削咲" },
{ "xie", "写携些解邪械協謝寫契" },
{ "xin", "心信新辛" },
{ "xing", "行形性幸型星興" },
{ "xiong", "兄胸" },
{ "xiu", "休秀修" },
{ "xu", "須需許續緒続" },
{ "xuan", "選懸" },
{ "xue", "学雪削靴學" },
{ "xun", "訓訊" },
{ "ya", "呀押壓" },
{ "yan", "言顔研煙嚴厳験驗塩" },
{ "yang", "央洋陽樣様" },
{ "yao", "要揺腰薬曜" },
{ "ye", "也野夜邪業葉" },
{ "yi", "一已亦依以移意医易伊役異億義議藝醫訳" },
{ "yin", "因引音飲銀" },
{ "ying", "英迎影映應營営" },
{ "yong", "永用泳擁" },
{ "you", "又有右友由尤油遊郵誘優" },
{ "yu", "予育余雨浴欲愈御宇域語於魚與込" },
{ "yuan", "元原源院員円園遠猿願" },
{ "yue", "月越約楽" },
{ "yun", "雲伝運" },
{ "za", "雑" },
{ "zai", "在再載災" },
{ "zang", "蔵" },
{ "zao", "早造" },
{ "ze", "則擇責" },
{ "zen", "怎" },
{ "zeng", "曾增増" },
{ "zha", "札" },
{ "zhai", "宅擇" },
{ "zhan", "站展戰戦" },
{ "zhang", "丈長障帳張" },
{ "zhao", "找着朝招" },
{ "zhe", "者這" },
{ "zhen", "真震針" },
{ "zheng", "正整争政爭" },
{ "zhi", "之只知支止制至治直指值置智値紙製質誌織隻識職執" },
{ "zhong", "中种終重種眾" },
{ "zhou", "周州昼宙洲週" },
{ "zhu", "助主住柱株祝逐注著諸屬術" },
{ "zhuan", "专專転" },
{ "zhuang", "状狀" },
{ "zhui", "追" },
{ "zhun", "準" },
{ "zhuo", "着" },
{ "zi", "子自字姉資" },
{ "zong", "總" },
{ "zuo", "左做昨坐座作" },
{ "zu", "足祖族卒組" },
{ "zui", "最酔" },
{ "zou", "走" },
{NULL, NULL}
};
#endif
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_ime_pinyin_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 keyboard of Pinyin input method.
* @param obj pointer to a Pinyin input method object
* @param dict pointer to a Pinyin input method keyboard
*/
void lv_ime_pinyin_set_keyboard(lv_obj_t * obj, lv_obj_t * kb)
{
if(kb) {
LV_ASSERT_OBJ(kb, &lv_keyboard_class);
}
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
pinyin_ime->kb = kb;
lv_obj_set_parent(obj, lv_obj_get_parent(kb));
lv_obj_set_parent(pinyin_ime->cand_panel, lv_obj_get_parent(kb));
lv_obj_add_event(pinyin_ime->kb, lv_ime_pinyin_kb_event, LV_EVENT_VALUE_CHANGED, obj);
lv_obj_align_to(pinyin_ime->cand_panel, pinyin_ime->kb, LV_ALIGN_OUT_TOP_MID, 0, 0);
}
/**
* Set the dictionary of Pinyin input method.
* @param obj pointer to a Pinyin input method object
* @param dict pointer to a Pinyin input method dictionary
*/
void lv_ime_pinyin_set_dict(lv_obj_t * obj, lv_pinyin_dict_t * dict)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
init_pinyin_dict(obj, dict);
}
/**
* Set mode, 26-key input(k26) or 9-key input(k9).
* @param obj pointer to a Pinyin input method object
* @param mode the mode from 'lv_keyboard_mode_t'
*/
void lv_ime_pinyin_set_mode(lv_obj_t * obj, lv_ime_pinyin_mode_t mode)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
LV_ASSERT_OBJ(pinyin_ime->kb, &lv_keyboard_class);
pinyin_ime->mode = mode;
#if LV_IME_PINYIN_USE_K9_MODE
if(pinyin_ime->mode == LV_IME_PINYIN_MODE_K9) {
pinyin_k9_init_data(obj);
lv_keyboard_set_map(pinyin_ime->kb, LV_KEYBOARD_MODE_USER_1, (const char **)lv_btnm_def_pinyin_k9_map,
default_kb_ctrl_k9_map);
lv_keyboard_set_mode(pinyin_ime->kb, LV_KEYBOARD_MODE_USER_1);
}
#endif
}
/*=====================
* Getter functions
*====================*/
/**
* Set the dictionary of Pinyin input method.
* @param obj pointer to a Pinyin IME object
* @return pointer to the Pinyin IME keyboard
*/
lv_obj_t * lv_ime_pinyin_get_kb(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
return pinyin_ime->kb;
}
/**
* Set the dictionary of Pinyin input method.
* @param obj pointer to a Pinyin input method object
* @return pointer to the Pinyin input method candidate panel
*/
lv_obj_t * lv_ime_pinyin_get_cand_panel(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
return pinyin_ime->cand_panel;
}
const lv_pinyin_dict_t * lv_ime_pinyin_get_dict(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
return pinyin_ime->dict;
}
/*=====================
* Other functions
*====================*/
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_ime_pinyin_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
uint16_t py_str_i = 0;
uint16_t btnm_i = 0;
for(btnm_i = 0; btnm_i < (LV_IME_PINYIN_CAND_TEXT_NUM + 3); btnm_i++) {
if(btnm_i == 0) {
lv_btnm_def_pinyin_sel_map[btnm_i] = "<";
}
else if(btnm_i == (LV_IME_PINYIN_CAND_TEXT_NUM + 1)) {
lv_btnm_def_pinyin_sel_map[btnm_i] = ">";
}
else if(btnm_i == (LV_IME_PINYIN_CAND_TEXT_NUM + 2)) {
lv_btnm_def_pinyin_sel_map[btnm_i] = "";
}
else {
lv_pinyin_cand_str[py_str_i][0] = ' ';
lv_btnm_def_pinyin_sel_map[btnm_i] = lv_pinyin_cand_str[py_str_i];
py_str_i++;
}
}
pinyin_ime->mode = LV_IME_PINYIN_MODE_K26;
pinyin_ime->py_page = 0;
pinyin_ime->ta_count = 0;
pinyin_ime->cand_num = 0;
lv_memzero(pinyin_ime->input_char, sizeof(pinyin_ime->input_char));
lv_memzero(pinyin_ime->py_num, sizeof(pinyin_ime->py_num));
lv_memzero(pinyin_ime->py_pos, sizeof(pinyin_ime->py_pos));
lv_obj_add_flag(obj, LV_OBJ_FLAG_HIDDEN);
#if LV_IME_PINYIN_USE_DEFAULT_DICT
init_pinyin_dict(obj, lv_ime_pinyin_def_dict);
#endif
/* Init pinyin_ime->cand_panel */
pinyin_ime->cand_panel = lv_buttonmatrix_create(lv_obj_get_parent(obj));
lv_buttonmatrix_set_map(pinyin_ime->cand_panel, (const char **)lv_btnm_def_pinyin_sel_map);
lv_obj_set_size(pinyin_ime->cand_panel, LV_PCT(100), LV_PCT(5));
lv_obj_add_flag(pinyin_ime->cand_panel, LV_OBJ_FLAG_HIDDEN);
lv_buttonmatrix_set_one_checked(pinyin_ime->cand_panel, true);
lv_obj_remove_flag(pinyin_ime->cand_panel, LV_OBJ_FLAG_CLICK_FOCUSABLE);
/* Set cand_panel style*/
// Default style
lv_obj_set_style_bg_opa(pinyin_ime->cand_panel, LV_OPA_0, 0);
lv_obj_set_style_border_width(pinyin_ime->cand_panel, 0, 0);
lv_obj_set_style_pad_all(pinyin_ime->cand_panel, 8, 0);
lv_obj_set_style_pad_gap(pinyin_ime->cand_panel, 0, 0);
lv_obj_set_style_radius(pinyin_ime->cand_panel, 0, 0);
lv_obj_set_style_pad_gap(pinyin_ime->cand_panel, 0, 0);
lv_obj_set_style_base_dir(pinyin_ime->cand_panel, LV_BASE_DIR_LTR, 0);
// LV_PART_ITEMS style
lv_obj_set_style_radius(pinyin_ime->cand_panel, 12, LV_PART_ITEMS);
lv_obj_set_style_bg_color(pinyin_ime->cand_panel, lv_color_white(), LV_PART_ITEMS);
lv_obj_set_style_bg_opa(pinyin_ime->cand_panel, LV_OPA_0, LV_PART_ITEMS);
lv_obj_set_style_shadow_opa(pinyin_ime->cand_panel, LV_OPA_0, LV_PART_ITEMS);
// LV_PART_ITEMS | LV_STATE_PRESSED style
lv_obj_set_style_bg_opa(pinyin_ime->cand_panel, LV_OPA_COVER, LV_PART_ITEMS | LV_STATE_PRESSED);
lv_obj_set_style_bg_color(pinyin_ime->cand_panel, lv_color_white(), LV_PART_ITEMS | LV_STATE_PRESSED);
/* event handler */
lv_obj_add_event(pinyin_ime->cand_panel, lv_ime_pinyin_cand_panel_event, LV_EVENT_VALUE_CHANGED, obj);
lv_obj_add_event(obj, lv_ime_pinyin_style_change_event, LV_EVENT_STYLE_CHANGED, NULL);
#if LV_IME_PINYIN_USE_K9_MODE
pinyin_ime->k9_input_str_len = 0;
pinyin_ime->k9_py_ll_pos = 0;
pinyin_ime->k9_legal_py_count = 0;
lv_memzero(pinyin_ime->k9_input_str, LV_IME_PINYIN_K9_MAX_INPUT);
pinyin_k9_init_data(obj);
_lv_ll_init(&(pinyin_ime->k9_legal_py_ll), sizeof(ime_pinyin_k9_py_str_t));
#endif
}
static void lv_ime_pinyin_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
if(lv_obj_is_valid(pinyin_ime->kb))
lv_obj_delete(pinyin_ime->kb);
if(lv_obj_is_valid(pinyin_ime->cand_panel))
lv_obj_delete(pinyin_ime->cand_panel);
}
static void lv_ime_pinyin_kb_event(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * kb = lv_event_get_target(e);
lv_obj_t * obj = lv_event_get_user_data(e);
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
#if LV_IME_PINYIN_USE_K9_MODE
static const char * k9_py_map[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
#endif
if(code == LV_EVENT_VALUE_CHANGED) {
uint16_t btn_id = lv_buttonmatrix_get_selected_button(kb);
if(btn_id == LV_BUTTONMATRIX_BUTTON_NONE) return;
const char * txt = lv_buttonmatrix_get_button_text(kb, lv_buttonmatrix_get_selected_button(kb));
if(txt == NULL) return;
lv_obj_t * ta = lv_keyboard_get_textarea(pinyin_ime->kb);
#if LV_IME_PINYIN_USE_K9_MODE
if(pinyin_ime->mode == LV_IME_PINYIN_MODE_K9) {
uint16_t tmp_button_str_len = lv_strlen(pinyin_ime->input_char);
if((btn_id >= 16) && (tmp_button_str_len > 0) && (btn_id < (16 + LV_IME_PINYIN_K9_CAND_TEXT_NUM))) {
lv_memzero(pinyin_ime->input_char, sizeof(pinyin_ime->input_char));
strcat(pinyin_ime->input_char, txt);
pinyin_input_proc(obj);
for(int index = 0; index < tmp_button_str_len; index++) {
lv_textarea_delete_char(ta);
}
pinyin_ime->ta_count = tmp_button_str_len;
pinyin_ime->k9_input_str_len = tmp_button_str_len;
lv_textarea_add_text(ta, pinyin_ime->input_char);
return;
}
}
#endif
if(strcmp(txt, "Enter") == 0 || strcmp(txt, LV_SYMBOL_NEW_LINE) == 0) {
pinyin_ime_clear_data(obj);
lv_obj_add_flag(pinyin_ime->cand_panel, LV_OBJ_FLAG_HIDDEN);
}
else if(strcmp(txt, LV_SYMBOL_BACKSPACE) == 0) {
// del input char
if(pinyin_ime->ta_count > 0) {
if(pinyin_ime->mode == LV_IME_PINYIN_MODE_K26)
pinyin_ime->input_char[pinyin_ime->ta_count - 1] = '\0';
#if LV_IME_PINYIN_USE_K9_MODE
else
pinyin_ime->k9_input_str[pinyin_ime->ta_count - 1] = '\0';
#endif
pinyin_ime->ta_count--;
if(pinyin_ime->ta_count <= 0) {
pinyin_ime_clear_data(obj);
lv_obj_add_flag(pinyin_ime->cand_panel, LV_OBJ_FLAG_HIDDEN);
}
else if(pinyin_ime->mode == LV_IME_PINYIN_MODE_K26) {
pinyin_input_proc(obj);
}
#if LV_IME_PINYIN_USE_K9_MODE
else if(pinyin_ime->mode == LV_IME_PINYIN_MODE_K9) {
pinyin_ime->k9_input_str_len = lv_strlen(pinyin_ime->input_char) - 1;
pinyin_k9_get_legal_py(obj, pinyin_ime->k9_input_str, k9_py_map);
pinyin_k9_fill_cand(obj);
pinyin_input_proc(obj);
pinyin_ime->ta_count--;
}
#endif
}
}
else if((strcmp(txt, "ABC") == 0) || (strcmp(txt, "abc") == 0) || (strcmp(txt, "1#") == 0) ||
(strcmp(txt, LV_SYMBOL_OK) == 0)) {
pinyin_ime_clear_data(obj);
return;
}
else if(strcmp(txt, "123") == 0) {
for(uint16_t i = 0; i < lv_strlen(txt); i++)
lv_textarea_delete_char(ta);
pinyin_ime_clear_data(obj);
lv_textarea_set_cursor_pos(ta, LV_TEXTAREA_CURSOR_LAST);
lv_ime_pinyin_set_mode(obj, LV_IME_PINYIN_MODE_K9_NUMBER);
lv_keyboard_set_mode(kb, LV_KEYBOARD_MODE_NUMBER);
lv_obj_add_flag(pinyin_ime->cand_panel, LV_OBJ_FLAG_HIDDEN);
}
else if(strcmp(txt, LV_SYMBOL_KEYBOARD) == 0) {
if(pinyin_ime->mode == LV_IME_PINYIN_MODE_K26) {
lv_ime_pinyin_set_mode(obj, LV_IME_PINYIN_MODE_K9);
}
else if(pinyin_ime->mode == LV_IME_PINYIN_MODE_K9) {
lv_ime_pinyin_set_mode(obj, LV_IME_PINYIN_MODE_K26);
lv_keyboard_set_mode(pinyin_ime->kb, LV_KEYBOARD_MODE_TEXT_LOWER);
}
else if(pinyin_ime->mode == LV_IME_PINYIN_MODE_K9_NUMBER) {
lv_ime_pinyin_set_mode(obj, LV_IME_PINYIN_MODE_K9);
}
pinyin_ime_clear_data(obj);
}
else if((pinyin_ime->mode == LV_IME_PINYIN_MODE_K26) && ((txt[0] >= 'a' && txt[0] <= 'z') || (txt[0] >= 'A' &&
txt[0] <= 'Z'))) {
strcat(pinyin_ime->input_char, txt);
pinyin_input_proc(obj);
pinyin_ime->ta_count++;
}
#if LV_IME_PINYIN_USE_K9_MODE
else if((pinyin_ime->mode == LV_IME_PINYIN_MODE_K9) && (txt[0] >= 'a' && txt[0] <= 'z')) {
for(uint16_t i = 0; i < 8; i++) {
if((strcmp(txt, k9_py_map[i]) == 0) || (strcmp(txt, "abc ") == 0)) {
if(strcmp(txt, "abc ") == 0) pinyin_ime->k9_input_str_len += lv_strlen(k9_py_map[i]) + 1;
else pinyin_ime->k9_input_str_len += lv_strlen(k9_py_map[i]);
pinyin_ime->k9_input_str[pinyin_ime->ta_count] = 50 + i;
pinyin_ime->k9_input_str[pinyin_ime->ta_count + 1] = '\0';
break;
}
}
pinyin_k9_get_legal_py(obj, pinyin_ime->k9_input_str, k9_py_map);
pinyin_k9_fill_cand(obj);
pinyin_input_proc(obj);
}
else if(strcmp(txt, LV_SYMBOL_LEFT) == 0) {
pinyin_k9_cand_page_proc(obj, 0);
}
else if(strcmp(txt, LV_SYMBOL_RIGHT) == 0) {
pinyin_k9_cand_page_proc(obj, 1);
}
#endif
}
}
static void lv_ime_pinyin_cand_panel_event(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * cand_panel = lv_event_get_target(e);
lv_obj_t * obj = (lv_obj_t *)lv_event_get_user_data(e);
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
if(code == LV_EVENT_VALUE_CHANGED) {
lv_obj_t * ta = lv_keyboard_get_textarea(pinyin_ime->kb);
if(ta == NULL) return;
uint32_t id = lv_buttonmatrix_get_selected_button(cand_panel);
if(id == LV_BUTTONMATRIX_BUTTON_NONE) {
return;
}
else if(id == 0) {
pinyin_page_proc(obj, 0);
return;
}
else if(id == (LV_IME_PINYIN_CAND_TEXT_NUM + 1)) {
pinyin_page_proc(obj, 1);
return;
}
const char * txt = lv_buttonmatrix_get_button_text(cand_panel, id);
uint16_t index = 0;
for(index = 0; index < pinyin_ime->ta_count; index++)
lv_textarea_delete_char(ta);
lv_textarea_add_text(ta, txt);
pinyin_ime_clear_data(obj);
}
}
static void pinyin_input_proc(lv_obj_t * obj)
{
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
pinyin_ime->cand_str = pinyin_search_matching(obj, pinyin_ime->input_char, &pinyin_ime->cand_num);
if(pinyin_ime->cand_str == NULL) {
return;
}
pinyin_ime->py_page = 0;
for(uint8_t i = 0; i < LV_IME_PINYIN_CAND_TEXT_NUM; i++) {
memset(lv_pinyin_cand_str[i], 0x00, sizeof(lv_pinyin_cand_str[i]));
lv_pinyin_cand_str[i][0] = ' ';
}
// fill buf
for(uint8_t i = 0; (i < pinyin_ime->cand_num && i < LV_IME_PINYIN_CAND_TEXT_NUM); i++) {
for(uint8_t j = 0; j < 3; j++) {
lv_pinyin_cand_str[i][j] = pinyin_ime->cand_str[i * 3 + j];
}
}
lv_obj_remove_flag(pinyin_ime->cand_panel, LV_OBJ_FLAG_HIDDEN);
}
static void pinyin_page_proc(lv_obj_t * obj, uint16_t dir)
{
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
uint16_t page_num = pinyin_ime->cand_num / LV_IME_PINYIN_CAND_TEXT_NUM;
uint16_t remainder = pinyin_ime->cand_num % LV_IME_PINYIN_CAND_TEXT_NUM;
if(dir == 0) {
if(pinyin_ime->py_page) {
pinyin_ime->py_page--;
}
}
else {
if(remainder == 0) {
page_num -= 1;
}
if(pinyin_ime->py_page < page_num) {
pinyin_ime->py_page++;
}
else return;
}
for(uint8_t i = 0; i < LV_IME_PINYIN_CAND_TEXT_NUM; i++) {
memset(lv_pinyin_cand_str[i], 0x00, sizeof(lv_pinyin_cand_str[i]));
lv_pinyin_cand_str[i][0] = ' ';
}
// fill buf
uint16_t offset = pinyin_ime->py_page * (3 * LV_IME_PINYIN_CAND_TEXT_NUM);
for(uint8_t i = 0; (i < pinyin_ime->cand_num && i < LV_IME_PINYIN_CAND_TEXT_NUM); i++) {
if((remainder > 0) && (pinyin_ime->py_page == page_num)) {
if(i > remainder)
break;
}
for(uint8_t j = 0; j < 3; j++) {
lv_pinyin_cand_str[i][j] = pinyin_ime->cand_str[offset + (i * 3) + j];
}
}
}
static void lv_ime_pinyin_style_change_event(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
if(code == LV_EVENT_STYLE_CHANGED) {
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_obj_set_style_text_font(pinyin_ime->cand_panel, font, 0);
}
}
static void init_pinyin_dict(lv_obj_t * obj, const lv_pinyin_dict_t * dict)
{
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
char headletter = 'a';
uint16_t offset_sum = 0;
uint16_t offset_count = 0;
uint16_t letter_calc = 0;
pinyin_ime->dict = dict;
for(uint16_t i = 0; ; i++) {
if((NULL == (dict[i].py)) || (NULL == (dict[i].py_mb))) {
headletter = dict[i - 1].py[0];
letter_calc = headletter - 'a';
pinyin_ime->py_num[letter_calc] = offset_count;
break;
}
if(headletter == (dict[i].py[0])) {
offset_count++;
}
else {
headletter = dict[i].py[0];
letter_calc = headletter - 'a';
pinyin_ime->py_num[letter_calc - 1] = offset_count;
offset_sum += offset_count;
pinyin_ime->py_pos[letter_calc] = offset_sum;
offset_count = 1;
}
}
}
static char * pinyin_search_matching(lv_obj_t * obj, char * py_str, uint16_t * cand_num)
{
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
const lv_pinyin_dict_t * cpHZ;
uint8_t index, len = 0, offset;
volatile uint8_t count = 0;
if(*py_str == '\0') return NULL;
if(*py_str == 'i') return NULL;
if(*py_str == 'u') return NULL;
if(*py_str == 'v') return NULL;
offset = py_str[0] - 'a';
len = lv_strlen(py_str);
cpHZ = &pinyin_ime->dict[pinyin_ime->py_pos[offset]];
count = pinyin_ime->py_num[offset];
while(count--) {
for(index = 0; index < len; index++) {
if(*(py_str + index) != *((cpHZ->py) + index)) {
break;
}
}
// perfect match
if(len == 1 || index == len) {
// The Chinese character in UTF-8 encoding format is 3 bytes
* cand_num = lv_strlen((const char *)(cpHZ->py_mb)) / 3;
return (char *)(cpHZ->py_mb);
}
cpHZ++;
}
return NULL;
}
static void pinyin_ime_clear_data(lv_obj_t * obj)
{
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
#if LV_IME_PINYIN_USE_K9_MODE
if(pinyin_ime->mode == LV_IME_PINYIN_MODE_K9) {
pinyin_ime->k9_input_str_len = 0;
pinyin_ime->k9_py_ll_pos = 0;
pinyin_ime->k9_legal_py_count = 0;
lv_memzero(pinyin_ime->k9_input_str, LV_IME_PINYIN_K9_MAX_INPUT);
lv_memzero(lv_pinyin_k9_cand_str, sizeof(lv_pinyin_k9_cand_str));
lv_strcpy(lv_pinyin_k9_cand_str[LV_IME_PINYIN_K9_CAND_TEXT_NUM], LV_SYMBOL_RIGHT"\0");
lv_strcpy(lv_pinyin_k9_cand_str[LV_IME_PINYIN_K9_CAND_TEXT_NUM + 1], "\0");
}
#endif
pinyin_ime->ta_count = 0;
lv_memzero(lv_pinyin_cand_str, (sizeof(lv_pinyin_cand_str)));
lv_memzero(pinyin_ime->input_char, sizeof(pinyin_ime->input_char));
lv_obj_add_flag(pinyin_ime->cand_panel, LV_OBJ_FLAG_HIDDEN);
}
#if LV_IME_PINYIN_USE_K9_MODE
static void pinyin_k9_init_data(lv_obj_t * obj)
{
LV_UNUSED(obj);
uint16_t py_str_i = 0;
uint16_t btnm_i = 0;
for(btnm_i = 19; btnm_i < (LV_IME_PINYIN_K9_CAND_TEXT_NUM + 21); btnm_i++) {
if(py_str_i == LV_IME_PINYIN_K9_CAND_TEXT_NUM) {
lv_strcpy(lv_pinyin_k9_cand_str[py_str_i], LV_SYMBOL_RIGHT"\0");
}
else if(py_str_i == LV_IME_PINYIN_K9_CAND_TEXT_NUM + 1) {
lv_strcpy(lv_pinyin_k9_cand_str[py_str_i], "\0");
}
else {
lv_strcpy(lv_pinyin_k9_cand_str[py_str_i], " \0");
}
lv_btnm_def_pinyin_k9_map[btnm_i] = lv_pinyin_k9_cand_str[py_str_i];
py_str_i++;
}
default_kb_ctrl_k9_map[0] = LV_KEYBOARD_CTRL_BUTTON_FLAGS | 1;
default_kb_ctrl_k9_map[4] = LV_KEYBOARD_CTRL_BUTTON_FLAGS | 1;
default_kb_ctrl_k9_map[5] = LV_KEYBOARD_CTRL_BUTTON_FLAGS | 1;
default_kb_ctrl_k9_map[9] = LV_KEYBOARD_CTRL_BUTTON_FLAGS | 1;
default_kb_ctrl_k9_map[10] = LV_KEYBOARD_CTRL_BUTTON_FLAGS | 1;
default_kb_ctrl_k9_map[14] = LV_KEYBOARD_CTRL_BUTTON_FLAGS | 1;
default_kb_ctrl_k9_map[15] = LV_KEYBOARD_CTRL_BUTTON_FLAGS | 1;
default_kb_ctrl_k9_map[LV_IME_PINYIN_K9_CAND_TEXT_NUM + 16] = LV_KEYBOARD_CTRL_BUTTON_FLAGS | 1;
}
static void pinyin_k9_get_legal_py(lv_obj_t * obj, char * k9_input, const char * py9_map[])
{
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
uint16_t len = lv_strlen(k9_input);
if((len == 0) || (len >= LV_IME_PINYIN_K9_MAX_INPUT)) {
return;
}
char py_comp[LV_IME_PINYIN_K9_MAX_INPUT] = {0};
int mark[LV_IME_PINYIN_K9_MAX_INPUT] = {0};
int index = 0;
int flag = 0;
uint16_t count = 0;
uint32_t ll_len = 0;
ime_pinyin_k9_py_str_t * ll_index = NULL;
ll_len = _lv_ll_get_len(&pinyin_ime->k9_legal_py_ll);
ll_index = _lv_ll_get_head(&pinyin_ime->k9_legal_py_ll);
while(index != -1) {
if(index == len) {
if(pinyin_k9_is_valid_py(obj, py_comp)) {
if((count >= ll_len) || (ll_len == 0)) {
ll_index = _lv_ll_ins_tail(&pinyin_ime->k9_legal_py_ll);
lv_strcpy(ll_index->py_str, py_comp);
}
else if((count < ll_len)) {
lv_strcpy(ll_index->py_str, py_comp);
ll_index = _lv_ll_get_next(&pinyin_ime->k9_legal_py_ll, ll_index);
}
count++;
}
index--;
}
else {
flag = mark[index];
if((size_t)flag < lv_strlen(py9_map[k9_input[index] - '2'])) {
py_comp[index] = py9_map[k9_input[index] - '2'][flag];
mark[index] = mark[index] + 1;
index++;
}
else {
mark[index] = 0;
index--;
}
}
}
if(count > 0) {
pinyin_ime->ta_count++;
pinyin_ime->k9_legal_py_count = count;
}
}
/*true: visible; false: not visible*/
static bool pinyin_k9_is_valid_py(lv_obj_t * obj, char * py_str)
{
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
const lv_pinyin_dict_t * cpHZ = NULL;
uint8_t index = 0, len = 0, offset = 0;
volatile uint8_t count = 0;
if(*py_str == '\0') return false;
if(*py_str == 'i') return false;
if(*py_str == 'u') return false;
if(*py_str == 'v') return false;
offset = py_str[0] - 'a';
len = lv_strlen(py_str);
cpHZ = &pinyin_ime->dict[pinyin_ime->py_pos[offset]];
count = pinyin_ime->py_num[offset];
while(count--) {
for(index = 0; index < len; index++) {
if(*(py_str + index) != *((cpHZ->py) + index)) {
break;
}
}
// perfect match
if(len == 1 || index == len) {
return true;
}
cpHZ++;
}
return false;
}
static void pinyin_k9_fill_cand(lv_obj_t * obj)
{
uint16_t index = 0, tmp_len = 0;
ime_pinyin_k9_py_str_t * ll_index = NULL;
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
tmp_len = pinyin_ime->k9_legal_py_count;
if(tmp_len != cand_len) {
lv_memzero(lv_pinyin_k9_cand_str, sizeof(lv_pinyin_k9_cand_str));
lv_strcpy(lv_pinyin_k9_cand_str[LV_IME_PINYIN_K9_CAND_TEXT_NUM], LV_SYMBOL_RIGHT"\0");
lv_strcpy(lv_pinyin_k9_cand_str[LV_IME_PINYIN_K9_CAND_TEXT_NUM + 1], "\0");
cand_len = tmp_len;
}
ll_index = _lv_ll_get_head(&pinyin_ime->k9_legal_py_ll);
lv_strcpy(pinyin_ime->input_char, ll_index->py_str);
while(ll_index) {
if((index >= LV_IME_PINYIN_K9_CAND_TEXT_NUM) || \
(index >= pinyin_ime->k9_legal_py_count))
break;
lv_strcpy(lv_pinyin_k9_cand_str[index], ll_index->py_str);
ll_index = _lv_ll_get_next(&pinyin_ime->k9_legal_py_ll, ll_index); /*Find the next list*/
index++;
}
pinyin_ime->k9_py_ll_pos = index;
lv_obj_t * ta = lv_keyboard_get_textarea(pinyin_ime->kb);
for(index = 0; index < pinyin_ime->k9_input_str_len; index++) {
lv_textarea_delete_char(ta);
}
pinyin_ime->k9_input_str_len = lv_strlen(pinyin_ime->input_char);
lv_textarea_add_text(ta, pinyin_ime->input_char);
}
static void pinyin_k9_cand_page_proc(lv_obj_t * obj, uint16_t dir)
{
lv_ime_pinyin_t * pinyin_ime = (lv_ime_pinyin_t *)obj;
lv_obj_t * ta = lv_keyboard_get_textarea(pinyin_ime->kb);
uint16_t ll_len = _lv_ll_get_len(&pinyin_ime->k9_legal_py_ll);
if((ll_len > LV_IME_PINYIN_K9_CAND_TEXT_NUM) && (pinyin_ime->k9_legal_py_count > LV_IME_PINYIN_K9_CAND_TEXT_NUM)) {
ime_pinyin_k9_py_str_t * ll_index = NULL;
int count = 0;
ll_index = _lv_ll_get_head(&pinyin_ime->k9_legal_py_ll);
while(ll_index) {
if(count >= pinyin_ime->k9_py_ll_pos) break;
ll_index = _lv_ll_get_next(&pinyin_ime->k9_legal_py_ll, ll_index); /*Find the next list*/
count++;
}
if((NULL == ll_index) && (dir == 1)) return;
lv_memzero(lv_pinyin_k9_cand_str, sizeof(lv_pinyin_k9_cand_str));
lv_strcpy(lv_pinyin_k9_cand_str[LV_IME_PINYIN_K9_CAND_TEXT_NUM], LV_SYMBOL_RIGHT"\0");
lv_strcpy(lv_pinyin_k9_cand_str[LV_IME_PINYIN_K9_CAND_TEXT_NUM + 1], "\0");
// next page
if(dir == 1) {
count = 0;
while(ll_index) {
if(count >= (LV_IME_PINYIN_K9_CAND_TEXT_NUM - 1))
break;
lv_strcpy(lv_pinyin_k9_cand_str[count], ll_index->py_str);
ll_index = _lv_ll_get_next(&pinyin_ime->k9_legal_py_ll, ll_index); /*Find the next list*/
count++;
}
pinyin_ime->k9_py_ll_pos += count - 1;
}
// previous page
else {
count = LV_IME_PINYIN_K9_CAND_TEXT_NUM - 1;
ll_index = _lv_ll_get_prev(&pinyin_ime->k9_legal_py_ll, ll_index);
while(ll_index) {
if(count < 0) break;
lv_strcpy(lv_pinyin_k9_cand_str[count], ll_index->py_str);
ll_index = _lv_ll_get_prev(&pinyin_ime->k9_legal_py_ll, ll_index); /*Find the previous list*/
count--;
}
if(pinyin_ime->k9_py_ll_pos > LV_IME_PINYIN_K9_CAND_TEXT_NUM)
pinyin_ime->k9_py_ll_pos -= 1;
}
lv_textarea_set_cursor_pos(ta, LV_TEXTAREA_CURSOR_LAST);
}
}
#endif /*LV_IME_PINYIN_USE_K9_MODE*/
#endif /*LV_USE_IME_PINYIN*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/ime/lv_ime_pinyin.h | /**
* @file lv_ime_pinyin.h
*
*/
#ifndef LV_IME_PINYIN_H
#define LV_IME_PINYIN_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_IME_PINYIN != 0
/*********************
* DEFINES
*********************/
#define LV_IME_PINYIN_K9_MAX_INPUT 7
/**********************
* TYPEDEFS
**********************/
typedef enum {
LV_IME_PINYIN_MODE_K26,
LV_IME_PINYIN_MODE_K9,
LV_IME_PINYIN_MODE_K9_NUMBER,
} lv_ime_pinyin_mode_t;
/*Data of pinyin_dict*/
typedef struct {
const char * const py;
const char * const py_mb;
} lv_pinyin_dict_t;
/*Data of 9-key input(k9) mode*/
typedef struct {
char py_str[7];
} ime_pinyin_k9_py_str_t;
/*Data of lv_ime_pinyin*/
typedef struct {
lv_obj_t obj;
lv_obj_t * kb;
lv_obj_t * cand_panel;
const lv_pinyin_dict_t * dict;
lv_ll_t k9_legal_py_ll;
char * cand_str; /* Candidate string */
char input_char[16]; /* Input box character */
#if LV_IME_PINYIN_USE_K9_MODE
char k9_input_str[LV_IME_PINYIN_K9_MAX_INPUT + 1]; /* 9-key input(k9) mode input string */
uint16_t k9_py_ll_pos; /* Current pinyin map pages(k9) */
uint16_t k9_legal_py_count; /* Count of legal Pinyin numbers(k9) */
uint16_t k9_input_str_len; /* 9-key input(k9) mode input string max len */
#endif
uint16_t ta_count; /* The number of characters entered in the text box this time */
uint16_t cand_num; /* Number of candidates */
uint16_t py_page; /* Current pinyin map pages(k26) */
uint16_t py_num[26]; /* Number and length of Pinyin */
uint16_t py_pos[26]; /* Pinyin position */
lv_ime_pinyin_mode_t mode; /* Set mode, 1: 26-key input(k26), 0: 9-key input(k9). Default: 1. */
} lv_ime_pinyin_t;
/***********************
* GLOBAL VARIABLES
***********************/
extern const lv_obj_class_t lv_ime_pinyin_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
lv_obj_t * lv_ime_pinyin_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set the keyboard of Pinyin input method.
* @param obj pointer to a Pinyin input method object
* @param kb pointer to a Pinyin input method keyboard
*/
void lv_ime_pinyin_set_keyboard(lv_obj_t * obj, lv_obj_t * kb);
/**
* Set the dictionary of Pinyin input method.
* @param obj pointer to a Pinyin input method object
* @param dict pointer to a Pinyin input method dictionary
*/
void lv_ime_pinyin_set_dict(lv_obj_t * obj, lv_pinyin_dict_t * dict);
/**
* Set mode, 26-key input(k26) or 9-key input(k9).
* @param obj pointer to a Pinyin input method object
* @param mode the mode from 'lv_ime_pinyin_mode_t'
*/
void lv_ime_pinyin_set_mode(lv_obj_t * obj, lv_ime_pinyin_mode_t mode);
/*=====================
* Getter functions
*====================*/
/**
* Set the dictionary of Pinyin input method.
* @param obj pointer to a Pinyin IME object
* @return pointer to the Pinyin IME keyboard
*/
lv_obj_t * lv_ime_pinyin_get_kb(lv_obj_t * obj);
/**
* Set the dictionary of Pinyin input method.
* @param obj pointer to a Pinyin input method object
* @return pointer to the Pinyin input method candidate panel
*/
lv_obj_t * lv_ime_pinyin_get_cand_panel(lv_obj_t * obj);
/**
* Set the dictionary of Pinyin input method.
* @param obj pointer to a Pinyin input method object
* @return pointer to the Pinyin input method dictionary
*/
const lv_pinyin_dict_t * lv_ime_pinyin_get_dict(lv_obj_t * obj);
/*=====================
* Other functions
*====================*/
/**********************
* MACROS
**********************/
#endif /*LV_IME_PINYIN*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_USE_IME_PINYIN*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/gridnav/lv_gridnav.c | /**
* @file lv_gridnav.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_gridnav.h"
#if LV_USE_GRIDNAV
#include "../../misc/lv_assert.h"
#include "../../misc/lv_math.h"
#include "../../indev/lv_indev.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_gridnav_ctrl_t ctrl;
lv_obj_t * focused_obj;
} lv_gridnav_dsc_t;
typedef enum {
FIND_LEFT,
FIND_RIGHT,
FIND_TOP,
FIND_BOTTOM,
FIND_NEXT_ROW_FIRST_ITEM,
FIND_PREV_ROW_LAST_ITEM,
FIND_FIRST_ROW,
FIND_LAST_ROW,
} find_mode_t;
/**********************
* STATIC PROTOTYPES
**********************/
static void gridnav_event_cb(lv_event_t * e);
static lv_obj_t * find_chid(lv_obj_t * obj, lv_obj_t * start_child, find_mode_t mode);
static lv_obj_t * find_first_focusable(lv_obj_t * obj);
static lv_obj_t * find_last_focusable(lv_obj_t * obj);
static bool obj_is_focuable(lv_obj_t * obj);
static int32_t get_x_center(lv_obj_t * obj);
static int32_t get_y_center(lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_gridnav_add(lv_obj_t * obj, lv_gridnav_ctrl_t ctrl)
{
lv_gridnav_remove(obj); /*Be sure to not add gridnav twice*/
lv_gridnav_dsc_t * dsc = lv_malloc(sizeof(lv_gridnav_dsc_t));
LV_ASSERT_MALLOC(dsc);
dsc->ctrl = ctrl;
dsc->focused_obj = NULL;
lv_obj_add_event(obj, gridnav_event_cb, LV_EVENT_ALL, dsc);
lv_obj_remove_flag(obj, LV_OBJ_FLAG_SCROLL_WITH_ARROW);
}
void lv_gridnav_remove(lv_obj_t * obj)
{
lv_event_dsc_t * event_dsc = NULL;
uint32_t event_cnt = lv_obj_get_event_count(obj);
uint32_t i;
for(i = 0; i < event_cnt; i++) {
event_dsc = lv_obj_get_event_dsc(obj, i);
if(lv_event_dsc_get_cb(event_dsc) == gridnav_event_cb) {
break;
}
}
if(event_dsc) {
lv_free(lv_event_dsc_get_user_data(event_dsc));
lv_obj_remove_event(obj, i);
}
}
void lv_gridnav_set_focused(lv_obj_t * cont, lv_obj_t * to_focus, lv_anim_enable_t anim_en)
{
LV_ASSERT_NULL(to_focus);
uint32_t i;
uint32_t event_cnt = lv_obj_get_event_count(cont);
lv_gridnav_dsc_t * dsc = NULL;
for(i = 0; i < event_cnt; i++) {
lv_event_dsc_t * event_dsc = lv_obj_get_event_dsc(cont, i);
if(lv_event_dsc_get_cb(event_dsc) == gridnav_event_cb) {
dsc = lv_event_dsc_get_user_data(event_dsc);
break;
}
}
if(dsc == NULL) {
LV_LOG_WARN("`cont` is not a gridnav container");
return;
}
if(obj_is_focuable(to_focus) == false) {
LV_LOG_WARN("The object to focus is not focusable");
return;
}
if(dsc->focused_obj) {
lv_obj_remove_state(dsc->focused_obj, LV_STATE_FOCUSED | LV_STATE_FOCUS_KEY);
}
lv_obj_add_state(to_focus, LV_STATE_FOCUSED | LV_STATE_FOCUS_KEY);
lv_obj_scroll_to_view(to_focus, anim_en);
dsc->focused_obj = to_focus;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void gridnav_event_cb(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
lv_gridnav_dsc_t * dsc = lv_event_get_user_data(e);
lv_event_code_t code = lv_event_get_code(e);
if(code == LV_EVENT_KEY) {
uint32_t child_cnt = lv_obj_get_child_cnt(obj);
if(child_cnt == 0) return;
if(dsc->focused_obj == NULL) dsc->focused_obj = find_first_focusable(obj);
if(dsc->focused_obj == NULL) return;
uint32_t key = lv_event_get_key(e);
lv_obj_t * guess = NULL;
if(key == LV_KEY_RIGHT) {
if((dsc->ctrl & LV_GRIDNAV_CTRL_SCROLL_FIRST) && lv_obj_has_flag(dsc->focused_obj, LV_OBJ_FLAG_SCROLLABLE) &&
lv_obj_get_scroll_right(dsc->focused_obj) > 0) {
int32_t d = lv_obj_get_width(dsc->focused_obj) / 4;
if(d <= 0) d = 1;
lv_obj_scroll_by_bounded(dsc->focused_obj, -d, 0, LV_ANIM_ON);
}
else {
guess = find_chid(obj, dsc->focused_obj, FIND_RIGHT);
if(guess == NULL) {
if(dsc->ctrl & LV_GRIDNAV_CTRL_ROLLOVER) {
guess = find_chid(obj, dsc->focused_obj, FIND_NEXT_ROW_FIRST_ITEM);
if(guess == NULL) guess = find_first_focusable(obj);
}
else {
lv_group_focus_next(lv_obj_get_group(obj));
}
}
}
}
else if(key == LV_KEY_LEFT) {
if((dsc->ctrl & LV_GRIDNAV_CTRL_SCROLL_FIRST) && lv_obj_has_flag(dsc->focused_obj, LV_OBJ_FLAG_SCROLLABLE) &&
lv_obj_get_scroll_left(dsc->focused_obj) > 0) {
int32_t d = lv_obj_get_width(dsc->focused_obj) / 4;
if(d <= 0) d = 1;
lv_obj_scroll_by_bounded(dsc->focused_obj, d, 0, LV_ANIM_ON);
}
else {
guess = find_chid(obj, dsc->focused_obj, FIND_LEFT);
if(guess == NULL) {
if(dsc->ctrl & LV_GRIDNAV_CTRL_ROLLOVER) {
guess = find_chid(obj, dsc->focused_obj, FIND_PREV_ROW_LAST_ITEM);
if(guess == NULL) guess = find_last_focusable(obj);
}
else {
lv_group_focus_prev(lv_obj_get_group(obj));
}
}
}
}
else if(key == LV_KEY_DOWN) {
if((dsc->ctrl & LV_GRIDNAV_CTRL_SCROLL_FIRST) && lv_obj_has_flag(dsc->focused_obj, LV_OBJ_FLAG_SCROLLABLE) &&
lv_obj_get_scroll_bottom(dsc->focused_obj) > 0) {
int32_t d = lv_obj_get_height(dsc->focused_obj) / 4;
if(d <= 0) d = 1;
lv_obj_scroll_by_bounded(dsc->focused_obj, 0, -d, LV_ANIM_ON);
}
else {
guess = find_chid(obj, dsc->focused_obj, FIND_BOTTOM);
if(guess == NULL) {
if(dsc->ctrl & LV_GRIDNAV_CTRL_ROLLOVER) {
guess = find_chid(obj, dsc->focused_obj, FIND_FIRST_ROW);
}
else {
lv_group_focus_next(lv_obj_get_group(obj));
}
}
}
}
else if(key == LV_KEY_UP) {
if((dsc->ctrl & LV_GRIDNAV_CTRL_SCROLL_FIRST) && lv_obj_has_flag(dsc->focused_obj, LV_OBJ_FLAG_SCROLLABLE) &&
lv_obj_get_scroll_top(dsc->focused_obj) > 0) {
int32_t d = lv_obj_get_height(dsc->focused_obj) / 4;
if(d <= 0) d = 1;
lv_obj_scroll_by_bounded(dsc->focused_obj, 0, d, LV_ANIM_ON);
}
else {
guess = find_chid(obj, dsc->focused_obj, FIND_TOP);
if(guess == NULL) {
if(dsc->ctrl & LV_GRIDNAV_CTRL_ROLLOVER) {
guess = find_chid(obj, dsc->focused_obj, FIND_LAST_ROW);
}
else {
lv_group_focus_prev(lv_obj_get_group(obj));
}
}
}
}
else {
if(lv_group_get_focused(lv_obj_get_group(obj)) == obj) {
lv_obj_send_event(dsc->focused_obj, LV_EVENT_KEY, &key);
}
}
if(guess && guess != dsc->focused_obj) {
lv_obj_remove_state(dsc->focused_obj, LV_STATE_FOCUSED | LV_STATE_FOCUS_KEY);
lv_obj_add_state(guess, LV_STATE_FOCUSED | LV_STATE_FOCUS_KEY);
lv_obj_scroll_to_view(guess, LV_ANIM_ON);
dsc->focused_obj = guess;
}
}
else if(code == LV_EVENT_FOCUSED) {
if(dsc->focused_obj == NULL) dsc->focused_obj = find_first_focusable(obj);
if(dsc->focused_obj) {
lv_obj_add_state(dsc->focused_obj, LV_STATE_FOCUSED | LV_STATE_FOCUS_KEY);
lv_obj_remove_state(dsc->focused_obj, LV_STATE_PRESSED); /*Be sure the focuses obj is not stuck in pressed state*/
lv_obj_scroll_to_view(dsc->focused_obj, LV_ANIM_OFF);
}
}
else if(code == LV_EVENT_DEFOCUSED) {
if(dsc->focused_obj) {
lv_obj_remove_state(dsc->focused_obj, LV_STATE_FOCUSED | LV_STATE_FOCUS_KEY);
}
}
else if(code == LV_EVENT_CHILD_CREATED) {
lv_obj_t * child = lv_event_get_target(e);
if(lv_obj_get_parent(child) == obj) {
if(dsc->focused_obj == NULL) {
dsc->focused_obj = child;
if(lv_obj_has_state(obj, LV_STATE_FOCUSED)) {
lv_obj_add_state(child, LV_STATE_FOCUSED | LV_STATE_FOCUS_KEY);
lv_obj_scroll_to_view(child, LV_ANIM_OFF);
}
}
}
}
else if(code == LV_EVENT_CHILD_DELETED) {
/*This event bubble, so be sure this object's child was deleted.
*As we don't know which object was deleted we can't make the next focused.
*So make the first object focused*/
lv_obj_t * target = lv_event_get_target(e);
if(target == obj) {
dsc->focused_obj = find_first_focusable(obj);
}
}
else if(code == LV_EVENT_DELETE) {
lv_gridnav_remove(obj);
}
else if(code == LV_EVENT_PRESSED || code == LV_EVENT_PRESSING || code == LV_EVENT_PRESS_LOST ||
code == LV_EVENT_LONG_PRESSED || code == LV_EVENT_LONG_PRESSED_REPEAT ||
code == LV_EVENT_CLICKED || code == LV_EVENT_RELEASED) {
if(lv_group_get_focused(lv_obj_get_group(obj)) == obj) {
/*Forward press/release related event too*/
lv_indev_type_t t = lv_indev_get_type(lv_indev_active());
if(t == LV_INDEV_TYPE_ENCODER || t == LV_INDEV_TYPE_KEYPAD) {
lv_obj_send_event(dsc->focused_obj, code, lv_indev_active());
}
}
}
}
static lv_obj_t * find_chid(lv_obj_t * obj, lv_obj_t * start_child, find_mode_t mode)
{
int32_t x_start = get_x_center(start_child);
int32_t y_start = get_y_center(start_child);
uint32_t child_cnt = lv_obj_get_child_cnt(obj);
lv_obj_t * guess = NULL;
int32_t x_err_guess = LV_COORD_MAX;
int32_t y_err_guess = LV_COORD_MAX;
int32_t h_half = lv_obj_get_height(start_child) / 2;
int32_t h_max = lv_obj_get_height(obj) + lv_obj_get_scroll_top(obj) + lv_obj_get_scroll_bottom(obj);
uint32_t i;
for(i = 0; i < child_cnt; i++) {
lv_obj_t * child = lv_obj_get_child(obj, i);
if(child == start_child) continue;
if(obj_is_focuable(child) == false) continue;
int32_t x_err = 0;
int32_t y_err = 0;
switch(mode) {
case FIND_LEFT:
x_err = get_x_center(child) - x_start;
y_err = get_y_center(child) - y_start;
if(x_err >= 0) continue; /*It's on the right*/
if(LV_ABS(y_err) > h_half) continue; /*Too far*/
break;
case FIND_RIGHT:
x_err = get_x_center(child) - x_start;
y_err = get_y_center(child) - y_start;
if(x_err <= 0) continue; /*It's on the left*/
if(LV_ABS(y_err) > h_half) continue; /*Too far*/
break;
case FIND_TOP:
x_err = get_x_center(child) - x_start;
y_err = get_y_center(child) - y_start;
if(y_err >= 0) continue; /*It's on the bottom*/
break;
case FIND_BOTTOM:
x_err = get_x_center(child) - x_start;
y_err = get_y_center(child) - y_start;
if(y_err <= 0) continue; /*It's on the top*/
break;
case FIND_NEXT_ROW_FIRST_ITEM:
y_err = get_y_center(child) - y_start;
if(y_err <= 0) continue; /*It's on the top*/
x_err = lv_obj_get_x(child);
break;
case FIND_PREV_ROW_LAST_ITEM:
y_err = get_y_center(child) - y_start;
if(y_err >= 0) continue; /*It's on the bottom*/
x_err = obj->coords.x2 - child->coords.x2;
break;
case FIND_FIRST_ROW:
x_err = get_x_center(child) - x_start;
y_err = lv_obj_get_y(child);
break;
case FIND_LAST_ROW:
x_err = get_x_center(child) - x_start;
y_err = h_max - lv_obj_get_y(child);
}
if(guess == NULL ||
(y_err * y_err + x_err * x_err < y_err_guess * y_err_guess + x_err_guess * x_err_guess)) {
guess = child;
x_err_guess = x_err;
y_err_guess = y_err;
}
}
return guess;
}
static lv_obj_t * find_first_focusable(lv_obj_t * obj)
{
uint32_t child_cnt = lv_obj_get_child_cnt(obj);
uint32_t i;
for(i = 0; i < child_cnt; i++) {
lv_obj_t * child = lv_obj_get_child(obj, i);
if(obj_is_focuable(child)) return child;
}
return NULL;
}
static lv_obj_t * find_last_focusable(lv_obj_t * obj)
{
uint32_t child_cnt = lv_obj_get_child_cnt(obj);
int32_t i;
for(i = child_cnt - 1; i >= 0; i--) {
lv_obj_t * child = lv_obj_get_child(obj, i);
if(obj_is_focuable(child)) return child;
}
return NULL;
}
static bool obj_is_focuable(lv_obj_t * obj)
{
if(lv_obj_has_flag(obj, LV_OBJ_FLAG_HIDDEN)) return false;
if(lv_obj_has_flag(obj, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_CLICK_FOCUSABLE)) return true;
else return false;
}
static int32_t get_x_center(lv_obj_t * obj)
{
return obj->coords.x1 + lv_area_get_width(&obj->coords) / 2;
}
static int32_t get_y_center(lv_obj_t * obj)
{
return obj->coords.y1 + lv_area_get_height(&obj->coords) / 2;
}
#endif /*LV_USE_GRIDNAV*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/gridnav/lv_gridnav.h | /**
* @file lv_templ.c
*
*/
/*********************
* INCLUDES
*********************/
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/*This typedef exists purely to keep -Wpedantic happy when the file is empty.*/
/*It can be removed.*/
typedef int _keep_pedantic_happy;
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**********************
* STATIC FUNCTIONS
**********************/
/**
* @file lv_gridnav.h
*
*/
#ifndef LV_GRIDFOCUS_H
#define LV_GRIDFOCUS_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../core/lv_obj.h"
#if LV_USE_GRIDNAV
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef enum {
LV_GRIDNAV_CTRL_NONE = 0x0,
/**
* If there is no next/previous object in a direction,
* the focus goes to the object in the next/previous row (on left/right keys)
* or first/last row (on up/down keys)
*/
LV_GRIDNAV_CTRL_ROLLOVER = 0x1,
/**
* If an arrow is pressed and the focused object can be scrolled in that direction
* then it will be scrolled instead of going to the next/previous object.
* If there is no more room for scrolling the next/previous object will be focused normally */
LV_GRIDNAV_CTRL_SCROLL_FIRST = 0x2,
} lv_gridnav_ctrl_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Add grid navigation feature to an object. It expects the children to be arranged
* into a grid-like layout. Although it's not required to have pixel perfect alignment.
* This feature makes possible to use keys to navigate among the children and focus them.
* The keys other than arrows and press/release related events
* are forwarded to the focused child.
* @param obj pointer to an object on which navigation should be applied.
* @param ctrl control flags from `lv_gridnav_ctrl_t`.
*/
void lv_gridnav_add(lv_obj_t * obj, lv_gridnav_ctrl_t ctrl);
/**
* Remove the grid navigation support from an object
* @param obj pointer to an object
*/
void lv_gridnav_remove(lv_obj_t * obj);
/**
* Manually focus an object on gridnav container
* @param cont pointer to a gridnav container
* @param to_focus pointer to an object to focus
* @param anim_en LV_ANIM_ON/OFF
*/
void lv_gridnav_set_focused(lv_obj_t * cont, lv_obj_t * to_focus, lv_anim_enable_t anim_en);
/**********************
* MACROS
**********************/
#endif /*LV_USE_GRIDNAV*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_GRIDFOCUS_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/imgfont/lv_imgfont.c | /**
* @file lv_imgfont.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_imgfont.h"
#if LV_USE_IMGFONT
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_font_t * font;
lv_imgfont_get_path_cb_t path_cb;
void * user_data;
} imgfont_dsc_t;
/**********************
* STATIC PROTOTYPES
**********************/
static const uint8_t * imgfont_get_glyph_bitmap(const lv_font_t * font, uint32_t unicode, uint8_t * bitmap_buf);
static bool imgfont_get_glyph_dsc(const lv_font_t * font, lv_font_glyph_dsc_t * dsc_out,
uint32_t unicode, uint32_t unicode_next);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_font_t * lv_imgfont_create(uint16_t height, lv_imgfont_get_path_cb_t path_cb, void * user_data)
{
LV_ASSERT_MSG(LV_IMGFONT_PATH_MAX_LEN > sizeof(lv_image_dsc_t),
"LV_IMGFONT_PATH_MAX_LEN must be greater than sizeof(lv_image_dsc_t)");
size_t size = sizeof(imgfont_dsc_t) + sizeof(lv_font_t);
imgfont_dsc_t * dsc = (imgfont_dsc_t *)lv_malloc(size);
if(dsc == NULL) return NULL;
lv_memzero(dsc, size);
dsc->font = (lv_font_t *)(((char *)dsc) + sizeof(imgfont_dsc_t));
dsc->path_cb = path_cb;
dsc->user_data = user_data;
lv_font_t * font = dsc->font;
font->dsc = dsc;
font->get_glyph_dsc = imgfont_get_glyph_dsc;
font->get_glyph_bitmap = imgfont_get_glyph_bitmap;
font->subpx = LV_FONT_SUBPX_NONE;
font->line_height = height;
font->base_line = 0;
font->underline_position = 0;
font->underline_thickness = 0;
return dsc->font;
}
void lv_imgfont_destroy(lv_font_t * font)
{
LV_ASSERT_NULL(font);
imgfont_dsc_t * dsc = (imgfont_dsc_t *)font->dsc;
lv_free(dsc);
}
/**********************
* STATIC FUNCTIONS
**********************/
static const uint8_t * imgfont_get_glyph_bitmap(const lv_font_t * font, uint32_t unicode, uint8_t * bitmap_buf)
{
LV_UNUSED(bitmap_buf);
LV_ASSERT_NULL(font);
imgfont_dsc_t * dsc = (imgfont_dsc_t *)font->dsc;
int32_t offset_y = 0;
const void * img_src = dsc->path_cb(dsc->font, unicode, 0, &offset_y, dsc->user_data);
return img_src;
}
static bool imgfont_get_glyph_dsc(const lv_font_t * font, lv_font_glyph_dsc_t * dsc_out,
uint32_t unicode, uint32_t unicode_next)
{
LV_ASSERT_NULL(font);
imgfont_dsc_t * dsc = (imgfont_dsc_t *)font->dsc;
LV_ASSERT_NULL(dsc);
if(dsc->path_cb == NULL) return false;
int32_t offset_y = 0;
const void * img_src = dsc->path_cb(dsc->font, unicode, unicode_next, &offset_y, dsc->user_data);
if(img_src == NULL) return false;
const lv_image_header_t * img_header;
#if LV_IMGFONT_USE_IMAGE_CACHE_HEADER
lv_color_t color = { 0 };
_lv_image_cache_entry_t * entry = _lv_image_cache_open(dsc->path, color, 0);
if(entry == NULL) {
return false;
}
img_header = &entry->dec_dsc.header;
#else
lv_image_header_t header;
if(lv_image_decoder_get_info(img_src, &header) != LV_RESULT_OK) {
return false;
}
img_header = &header;
#endif
dsc_out->is_placeholder = 0;
dsc_out->adv_w = img_header->w;
dsc_out->box_w = img_header->w;
dsc_out->box_h = img_header->h;
dsc_out->bpp = LV_IMGFONT_BPP; /* is image identifier */
dsc_out->ofs_x = 0;
dsc_out->ofs_y = offset_y;
return true;
}
#endif /*LV_USE_IMGFONT*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/imgfont/lv_imgfont.h | /**
* @file lv_imgfont.h
*
*/
#ifndef LV_IMGFONT_H
#define LV_IMGFONT_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_IMGFONT
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/* gets the image path name of this character */
typedef const void * (*lv_imgfont_get_path_cb_t)(const lv_font_t * font,
uint32_t unicode, uint32_t unicode_next,
int32_t * offset_y, void * user_data);
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Creates a image font with info parameter specified.
* @param height font size
* @param path_cb a function to get the image path name of character.
* @param user_data pointer to user data
* @return pointer to the new imgfont or NULL if create error.
*/
lv_font_t * lv_imgfont_create(uint16_t height, lv_imgfont_get_path_cb_t path_cb, void * user_data);
/**
* Destroy a image font that has been created.
* @param font pointer to image font handle.
*/
void lv_imgfont_destroy(lv_font_t * font);
/**********************
* MACROS
**********************/
#endif /*LV_USE_IMGFONT*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /* LV_IMGFONT_H */
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/file_explorer/lv_file_explorer.c | /**
* @file lv_file_explorer.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_file_explorer.h"
#if LV_USE_FILE_EXPLORER != 0
#include "../../core/lv_global.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_file_explorer_class
#define FILE_EXPLORER_QUICK_ACCESS_AREA_WIDTH (22)
#define FILE_EXPLORER_BROWSER_AREA_WIDTH (100 - FILE_EXPLORER_QUICK_ACCESS_AREA_WIDTH)
#define quick_access_list_button_style (LV_GLOBAL_DEFAULT()->fe_list_button_style)
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_file_explorer_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void browser_file_event_handler(lv_event_t * e);
#if LV_FILE_EXPLORER_QUICK_ACCESS
static void quick_access_event_handler(lv_event_t * e);
static void quick_access_area_event_handler(lv_event_t * e);
#endif
static void init_style(lv_obj_t * obj);
static void show_dir(lv_obj_t * obj, const char * path);
static void strip_ext(char * dir);
static void file_explorer_sort(lv_obj_t * obj);
static void sort_by_file_kind(lv_obj_t * tb, int16_t lo, int16_t hi);
static void exch_table_item(lv_obj_t * tb, int16_t i, int16_t j);
static bool is_end_with(const char * str1, const char * str2);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_file_explorer_class = {
.constructor_cb = lv_file_explorer_constructor,
.width_def = LV_SIZE_CONTENT,
.height_def = LV_SIZE_CONTENT,
.instance_size = sizeof(lv_file_explorer_t),
.base_class = &lv_obj_class,
.name = "file-explorer",
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_file_explorer_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
*====================*/
#if LV_FILE_EXPLORER_QUICK_ACCESS
void lv_file_explorer_set_quick_access_path(lv_obj_t * obj, lv_file_explorer_dir_t dir, const char * path)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
/*If path is unavailable */
if((path == NULL) || (lv_strlen(path) <= 0)) return;
char ** dir_str = NULL;
switch(dir) {
case LV_EXPLORER_HOME_DIR:
dir_str = &(explorer->home_dir);
break;
case LV_EXPLORER_MUSIC_DIR:
dir_str = &(explorer->music_dir);
break;
case LV_EXPLORER_PICTURES_DIR:
dir_str = &(explorer->pictures_dir);
break;
case LV_EXPLORER_VIDEO_DIR:
dir_str = &(explorer->video_dir);
break;
case LV_EXPLORER_DOCS_DIR:
dir_str = &(explorer->docs_dir);
break;
case LV_EXPLORER_FS_DIR:
dir_str = &(explorer->fs_dir);
break;
default:
return;
break;
}
/*Free the old text*/
if(*dir_str != NULL) {
lv_free(*dir_str);
*dir_str = NULL;
}
/*Allocate space for the new text*/
*dir_str = lv_strdup(path);
}
#endif
void lv_file_explorer_set_sort(lv_obj_t * obj, lv_file_explorer_sort_t sort)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
explorer->sort = sort;
file_explorer_sort(obj);
}
/*=====================
* Getter functions
*====================*/
const char * lv_file_explorer_get_selected_file_name(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
return explorer->sel_fn;
}
const char * lv_file_explorer_get_current_path(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
return explorer->current_path;
}
lv_obj_t * lv_file_explorer_get_file_table(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
return explorer->file_table;
}
lv_obj_t * lv_file_explorer_get_header(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
return explorer->head_area;
}
lv_obj_t * lv_file_explorer_get_quick_access_area(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
return explorer->quick_access_area;
}
lv_obj_t * lv_file_explorer_get_path_label(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
return explorer->path_label;
}
#if LV_FILE_EXPLORER_QUICK_ACCESS
lv_obj_t * lv_file_explorer_get_places_list(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
return explorer->list_places;
}
lv_obj_t * lv_file_explorer_get_device_list(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
return explorer->list_device;
}
#endif
lv_file_explorer_sort_t lv_file_explorer_get_sort(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
return explorer->sort;
}
/*=====================
* Other functions
*====================*/
void lv_file_explorer_open_dir(lv_obj_t * obj, const char * dir)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
show_dir(obj, dir);
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_file_explorer_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
#if LV_FILE_EXPLORER_QUICK_ACCESS
explorer->home_dir = NULL;
explorer->video_dir = NULL;
explorer->pictures_dir = NULL;
explorer->music_dir = NULL;
explorer->docs_dir = NULL;
explorer->fs_dir = NULL;
#endif
explorer->sort = LV_EXPLORER_SORT_NONE;
lv_memzero(explorer->current_path, sizeof(explorer->current_path));
lv_obj_set_size(obj, LV_PCT(100), LV_PCT(100));
lv_obj_set_flex_flow(obj, LV_FLEX_FLOW_COLUMN);
explorer->cont = lv_obj_create(obj);
lv_obj_set_width(explorer->cont, LV_PCT(100));
lv_obj_set_flex_grow(explorer->cont, 1);
#if LV_FILE_EXPLORER_QUICK_ACCESS
/*Quick access bar area on the left*/
explorer->quick_access_area = lv_obj_create(explorer->cont);
lv_obj_set_size(explorer->quick_access_area, LV_PCT(FILE_EXPLORER_QUICK_ACCESS_AREA_WIDTH), LV_PCT(100));
lv_obj_set_flex_flow(explorer->quick_access_area, LV_FLEX_FLOW_COLUMN);
lv_obj_add_event(explorer->quick_access_area, quick_access_area_event_handler, LV_EVENT_ALL,
explorer);
#endif
/*File table area on the right*/
explorer->browser_area = lv_obj_create(explorer->cont);
#if LV_FILE_EXPLORER_QUICK_ACCESS
lv_obj_set_size(explorer->browser_area, LV_PCT(FILE_EXPLORER_BROWSER_AREA_WIDTH), LV_PCT(100));
#else
lv_obj_set_size(explorer->browser_area, LV_PCT(100), LV_PCT(100));
#endif
lv_obj_set_flex_flow(explorer->browser_area, LV_FLEX_FLOW_COLUMN);
/*The area displayed above the file browse list(head)*/
explorer->head_area = lv_obj_create(explorer->browser_area);
lv_obj_set_size(explorer->head_area, LV_PCT(100), LV_PCT(14));
lv_obj_remove_flag(explorer->head_area, LV_OBJ_FLAG_SCROLLABLE);
#if LV_FILE_EXPLORER_QUICK_ACCESS
/*Two lists of quick access bar*/
lv_obj_t * btn;
/*list 1*/
explorer->list_device = lv_list_create(explorer->quick_access_area);
lv_obj_set_size(explorer->list_device, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_bg_color(lv_list_add_text(explorer->list_device, "DEVICE"), lv_palette_main(LV_PALETTE_ORANGE), 0);
btn = lv_list_add_button(explorer->list_device, NULL, LV_SYMBOL_DRIVE " File System");
lv_obj_add_event(btn, quick_access_event_handler, LV_EVENT_CLICKED, obj);
/*list 2*/
explorer->list_places = lv_list_create(explorer->quick_access_area);
lv_obj_set_size(explorer->list_places, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_bg_color(lv_list_add_text(explorer->list_places, "PLACES"), lv_palette_main(LV_PALETTE_LIME), 0);
btn = lv_list_add_button(explorer->list_places, NULL, LV_SYMBOL_HOME " HOME");
lv_obj_add_event(btn, quick_access_event_handler, LV_EVENT_CLICKED, obj);
btn = lv_list_add_button(explorer->list_places, NULL, LV_SYMBOL_VIDEO " Video");
lv_obj_add_event(btn, quick_access_event_handler, LV_EVENT_CLICKED, obj);
btn = lv_list_add_button(explorer->list_places, NULL, LV_SYMBOL_IMAGE " Pictures");
lv_obj_add_event(btn, quick_access_event_handler, LV_EVENT_CLICKED, obj);
btn = lv_list_add_button(explorer->list_places, NULL, LV_SYMBOL_AUDIO " Music");
lv_obj_add_event(btn, quick_access_event_handler, LV_EVENT_CLICKED, obj);
btn = lv_list_add_button(explorer->list_places, NULL, LV_SYMBOL_FILE " Documents");
lv_obj_add_event(btn, quick_access_event_handler, LV_EVENT_CLICKED, obj);
#endif
/*Show current path*/
explorer->path_label = lv_label_create(explorer->head_area);
lv_label_set_text(explorer->path_label, LV_SYMBOL_EYE_OPEN"https://lvgl.io");
lv_obj_center(explorer->path_label);
/*Table showing the contents of the table of contents*/
explorer->file_table = lv_table_create(explorer->browser_area);
lv_obj_set_size(explorer->file_table, LV_PCT(100), LV_PCT(86));
lv_table_set_col_width(explorer->file_table, 0, LV_PCT(100));
lv_table_set_col_cnt(explorer->file_table, 1);
lv_obj_add_event(explorer->file_table, browser_file_event_handler, LV_EVENT_ALL, obj);
/*only scroll up and down*/
lv_obj_set_scroll_dir(explorer->file_table, LV_DIR_TOP | LV_DIR_BOTTOM);
/*Initialize style*/
init_style(obj);
LV_TRACE_OBJ_CREATE("finished");
}
static void init_style(lv_obj_t * obj)
{
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
/*lv_file_explorer obj style*/
lv_obj_set_style_radius(obj, 0, 0);
lv_obj_set_style_bg_color(obj, lv_color_hex(0xf2f1f6), 0);
/*main container style*/
lv_obj_set_style_radius(explorer->cont, 0, 0);
lv_obj_set_style_bg_opa(explorer->cont, LV_OPA_0, 0);
lv_obj_set_style_border_width(explorer->cont, 0, 0);
lv_obj_set_style_outline_width(explorer->cont, 0, 0);
lv_obj_set_style_pad_column(explorer->cont, 0, 0);
lv_obj_set_style_pad_row(explorer->cont, 0, 0);
lv_obj_set_style_flex_flow(explorer->cont, LV_FLEX_FLOW_ROW, 0);
lv_obj_set_style_pad_all(explorer->cont, 0, 0);
lv_obj_set_style_layout(explorer->cont, LV_LAYOUT_FLEX, 0);
/*head cont style*/
lv_obj_set_style_radius(explorer->head_area, 0, 0);
lv_obj_set_style_border_width(explorer->head_area, 0, 0);
lv_obj_set_style_pad_top(explorer->head_area, 0, 0);
#if LV_FILE_EXPLORER_QUICK_ACCESS
/*Quick access bar container style*/
lv_obj_set_style_pad_all(explorer->quick_access_area, 0, 0);
lv_obj_set_style_pad_row(explorer->quick_access_area, 20, 0);
lv_obj_set_style_radius(explorer->quick_access_area, 0, 0);
lv_obj_set_style_border_width(explorer->quick_access_area, 1, 0);
lv_obj_set_style_outline_width(explorer->quick_access_area, 0, 0);
lv_obj_set_style_bg_color(explorer->quick_access_area, lv_color_hex(0xf2f1f6), 0);
#endif
/*File browser container style*/
lv_obj_set_style_pad_all(explorer->browser_area, 0, 0);
lv_obj_set_style_pad_row(explorer->browser_area, 0, 0);
lv_obj_set_style_radius(explorer->browser_area, 0, 0);
lv_obj_set_style_border_width(explorer->browser_area, 0, 0);
lv_obj_set_style_outline_width(explorer->browser_area, 0, 0);
lv_obj_set_style_bg_color(explorer->browser_area, lv_color_hex(0xffffff), 0);
/*Style of the table in the browser container*/
lv_obj_set_style_bg_color(explorer->file_table, lv_color_hex(0xffffff), 0);
lv_obj_set_style_pad_all(explorer->file_table, 0, 0);
lv_obj_set_style_radius(explorer->file_table, 0, 0);
lv_obj_set_style_border_width(explorer->file_table, 0, 0);
lv_obj_set_style_outline_width(explorer->file_table, 0, 0);
#if LV_FILE_EXPLORER_QUICK_ACCESS
/*Style of the list in the quick access bar*/
lv_obj_set_style_border_width(explorer->list_device, 0, 0);
lv_obj_set_style_outline_width(explorer->list_device, 0, 0);
lv_obj_set_style_radius(explorer->list_device, 0, 0);
lv_obj_set_style_pad_all(explorer->list_device, 0, 0);
lv_obj_set_style_border_width(explorer->list_places, 0, 0);
lv_obj_set_style_outline_width(explorer->list_places, 0, 0);
lv_obj_set_style_radius(explorer->list_places, 0, 0);
lv_obj_set_style_pad_all(explorer->list_places, 0, 0);
/*Style of the quick access list btn in the quick access bar*/
lv_style_init(&quick_access_list_button_style);
lv_style_set_border_width(&quick_access_list_button_style, 0);
lv_style_set_bg_color(&quick_access_list_button_style, lv_color_hex(0xf2f1f6));
uint32_t i, j;
for(i = 0; i < lv_obj_get_child_cnt(explorer->quick_access_area); i++) {
lv_obj_t * child = lv_obj_get_child(explorer->quick_access_area, i);
if(lv_obj_check_type(child, &lv_list_class)) {
for(j = 0; j < lv_obj_get_child_cnt(child); j++) {
lv_obj_t * list_child = lv_obj_get_child(child, j);
if(lv_obj_check_type(list_child, &lv_list_button_class)) {
lv_obj_add_style(list_child, &quick_access_list_button_style, 0);
}
}
}
}
#endif
}
#if LV_FILE_EXPLORER_QUICK_ACCESS
static void quick_access_event_handler(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * btn = lv_event_get_target(e);
lv_obj_t * obj = lv_event_get_user_data(e);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
if(code == LV_EVENT_CLICKED) {
char ** path = NULL;
lv_obj_t * label = lv_obj_get_child(btn, -1);
char * label_text = lv_label_get_text(label);
if((strcmp(label_text, LV_SYMBOL_HOME " HOME") == 0)) {
path = &(explorer->home_dir);
}
else if((strcmp(label_text, LV_SYMBOL_VIDEO " Video") == 0)) {
path = &(explorer->video_dir);
}
else if((strcmp(label_text, LV_SYMBOL_IMAGE " Pictures") == 0)) {
path = &(explorer->pictures_dir);
}
else if((strcmp(label_text, LV_SYMBOL_AUDIO " Music") == 0)) {
path = &(explorer->music_dir);
}
else if((strcmp(label_text, LV_SYMBOL_FILE " Documents") == 0)) {
path = &(explorer->docs_dir);
}
else if((strcmp(label_text, LV_SYMBOL_DRIVE " File System") == 0)) {
path = &(explorer->fs_dir);
}
if(path != NULL)
show_dir(obj, *path);
}
}
static void quick_access_area_event_handler(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * area = lv_event_get_target(e);
lv_obj_t * obj = lv_event_get_user_data(e);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
if(code == LV_EVENT_LAYOUT_CHANGED) {
if(lv_obj_has_flag(area, LV_OBJ_FLAG_HIDDEN))
lv_obj_set_size(explorer->browser_area, LV_PCT(100), LV_PCT(100));
else
lv_obj_set_size(explorer->browser_area, LV_PCT(FILE_EXPLORER_BROWSER_AREA_WIDTH), LV_PCT(100));
}
}
#endif
static void browser_file_event_handler(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_user_data(e);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
if(code == LV_EVENT_VALUE_CHANGED) {
char file_name[LV_FILE_EXPLORER_PATH_MAX_LEN];
const char * str_fn = NULL;
uint32_t row;
uint32_t col;
lv_memzero(file_name, sizeof(file_name));
lv_table_get_selected_cell(explorer->file_table, &row, &col);
str_fn = lv_table_get_cell_value(explorer->file_table, row, col);
str_fn = str_fn + 5;
if((strcmp(str_fn, ".") == 0)) return;
if((strcmp(str_fn, "..") == 0) && (lv_strlen(explorer->current_path) > 3)) {
strip_ext(explorer->current_path);
/*Remove the last '/' character*/
strip_ext(explorer->current_path);
lv_snprintf((char *)file_name, sizeof(file_name), "%s", explorer->current_path);
}
else {
if(strcmp(str_fn, "..") != 0) {
lv_snprintf((char *)file_name, sizeof(file_name), "%s%s", explorer->current_path, str_fn);
}
}
lv_fs_dir_t dir;
if(lv_fs_dir_open(&dir, file_name) == LV_FS_RES_OK) {
lv_fs_dir_close(&dir);
show_dir(obj, (char *)file_name);
}
else {
if(strcmp(str_fn, "..") != 0) {
explorer->sel_fn = str_fn;
lv_obj_send_event(obj, LV_EVENT_VALUE_CHANGED, NULL);
}
}
}
else if(code == LV_EVENT_SIZE_CHANGED) {
lv_table_set_col_width(explorer->file_table, 0, lv_obj_get_width(explorer->file_table));
}
else if((code == LV_EVENT_CLICKED) || (code == LV_EVENT_RELEASED)) {
lv_obj_send_event(obj, LV_EVENT_CLICKED, NULL);
}
}
static void show_dir(lv_obj_t * obj, const char * path)
{
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
char fn[LV_FILE_EXPLORER_PATH_MAX_LEN];
uint16_t index = 0;
lv_fs_dir_t dir;
lv_fs_res_t res;
res = lv_fs_dir_open(&dir, path);
if(res != LV_FS_RES_OK) {
LV_LOG_USER("Open dir error %d!", res);
return;
}
lv_table_set_cell_value_fmt(explorer->file_table, index++, 0, LV_SYMBOL_DIRECTORY " %s", ".");
lv_table_set_cell_value_fmt(explorer->file_table, index++, 0, LV_SYMBOL_DIRECTORY " %s", "..");
lv_table_set_cell_value(explorer->file_table, 0, 1, "0");
lv_table_set_cell_value(explorer->file_table, 1, 1, "0");
while(1) {
res = lv_fs_dir_read(&dir, fn);
if(res != LV_FS_RES_OK) {
LV_LOG_USER("Driver, file or directory is not exists %d!", res);
break;
}
/*fn is empty, if not more files to read*/
if(lv_strlen(fn) == 0) {
LV_LOG_USER("Not more files to read!");
break;
}
if((is_end_with(fn, ".png") == true) || (is_end_with(fn, ".PNG") == true) || \
(is_end_with(fn, ".jpg") == true) || (is_end_with(fn, ".JPG") == true) || \
(is_end_with(fn, ".bmp") == true) || (is_end_with(fn, ".BMP") == true) || \
(is_end_with(fn, ".gif") == true) || (is_end_with(fn, ".GIF") == true)) {
lv_table_set_cell_value_fmt(explorer->file_table, index, 0, LV_SYMBOL_IMAGE " %s", fn);
lv_table_set_cell_value(explorer->file_table, index, 1, "1");
}
else if((is_end_with(fn, ".mp3") == true) || (is_end_with(fn, ".MP3") == true)) {
lv_table_set_cell_value_fmt(explorer->file_table, index, 0, LV_SYMBOL_AUDIO " %s", fn);
lv_table_set_cell_value(explorer->file_table, index, 1, "2");
}
else if((is_end_with(fn, ".mp4") == true) || (is_end_with(fn, ".MP4") == true)) {
lv_table_set_cell_value_fmt(explorer->file_table, index, 0, LV_SYMBOL_VIDEO " %s", fn);
lv_table_set_cell_value(explorer->file_table, index, 1, "3");
}
else if((is_end_with(fn, ".") == true) || (is_end_with(fn, "..") == true)) {
/*is dir*/
continue;
}
else if(fn[0] == '/') {/*is dir*/
lv_table_set_cell_value_fmt(explorer->file_table, index, 0, LV_SYMBOL_DIRECTORY " %s", fn + 1);
lv_table_set_cell_value(explorer->file_table, index, 1, "0");
}
else {
lv_table_set_cell_value_fmt(explorer->file_table, index, 0, LV_SYMBOL_FILE " %s", fn);
lv_table_set_cell_value(explorer->file_table, index, 1, "4");
}
index++;
}
lv_fs_dir_close(&dir);
lv_table_set_row_cnt(explorer->file_table, index);
file_explorer_sort(obj);
lv_obj_send_event(obj, LV_EVENT_READY, NULL);
/*Move the table to the top*/
lv_obj_scroll_to_y(explorer->file_table, 0, LV_ANIM_OFF);
lv_memzero(explorer->current_path, sizeof(explorer->current_path));
lv_strncpy(explorer->current_path, path, sizeof(explorer->current_path) - 1);
lv_label_set_text_fmt(explorer->path_label, LV_SYMBOL_EYE_OPEN" %s", path);
size_t current_path_len = lv_strlen(explorer->current_path);
if((*((explorer->current_path) + current_path_len) != '/') && (current_path_len < LV_FILE_EXPLORER_PATH_MAX_LEN)) {
*((explorer->current_path) + current_path_len) = '/';
}
}
/*Remove the specified suffix*/
static void strip_ext(char * dir)
{
char * end = dir + lv_strlen(dir);
while(end >= dir && *end != '/') {
--end;
}
if(end > dir) {
*end = '\0';
}
else if(end == dir) {
*(end + 1) = '\0';
}
}
static void exch_table_item(lv_obj_t * tb, int16_t i, int16_t j)
{
const char * tmp;
tmp = lv_table_get_cell_value(tb, i, 0);
lv_table_set_cell_value(tb, 0, 2, tmp);
lv_table_set_cell_value(tb, i, 0, lv_table_get_cell_value(tb, j, 0));
lv_table_set_cell_value(tb, j, 0, lv_table_get_cell_value(tb, 0, 2));
tmp = lv_table_get_cell_value(tb, i, 1);
lv_table_set_cell_value(tb, 0, 2, tmp);
lv_table_set_cell_value(tb, i, 1, lv_table_get_cell_value(tb, j, 1));
lv_table_set_cell_value(tb, j, 1, lv_table_get_cell_value(tb, 0, 2));
}
static void file_explorer_sort(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_file_explorer_t * explorer = (lv_file_explorer_t *)obj;
uint16_t sum = lv_table_get_row_cnt(explorer->file_table);
if(sum > 1) {
switch(explorer->sort) {
case LV_EXPLORER_SORT_NONE:
break;
case LV_EXPLORER_SORT_KIND:
sort_by_file_kind(explorer->file_table, 0, (sum - 1));
break;
default:
break;
}
}
}
/*Quick sort 3 way*/
static void sort_by_file_kind(lv_obj_t * tb, int16_t lo, int16_t hi)
{
if(lo >= hi) return;
int16_t lt = lo;
int16_t i = lo + 1;
int16_t gt = hi;
const char * v = lv_table_get_cell_value(tb, lo, 1);
while(i <= gt) {
if(strcmp(lv_table_get_cell_value(tb, i, 1), v) < 0)
exch_table_item(tb, lt++, i++);
else if(strcmp(lv_table_get_cell_value(tb, i, 1), v) > 0)
exch_table_item(tb, i, gt--);
else
i++;
}
sort_by_file_kind(tb, lo, lt - 1);
sort_by_file_kind(tb, gt + 1, hi);
}
static bool is_end_with(const char * str1, const char * str2)
{
if(str1 == NULL || str2 == NULL)
return false;
uint16_t len1 = lv_strlen(str1);
uint16_t len2 = lv_strlen(str2);
if((len1 < len2) || (len1 == 0 || len2 == 0))
return false;
while(len2 >= 1) {
if(str2[len2 - 1] != str1[len1 - 1])
return false;
len2--;
len1--;
}
return true;
}
#endif /*LV_USE_FILE_EXPLORER*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/file_explorer/lv_file_explorer.h | /**
* @file lv_file_explorer.h
*
*/
#ifndef LV_FILE_EXPLORER_H
#define LV_FILE_EXPLORER_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_FILE_EXPLORER != 0
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef enum {
LV_EXPLORER_SORT_NONE,
LV_EXPLORER_SORT_KIND,
} lv_file_explorer_sort_t;
#if LV_FILE_EXPLORER_QUICK_ACCESS
typedef enum {
LV_EXPLORER_HOME_DIR,
LV_EXPLORER_MUSIC_DIR,
LV_EXPLORER_PICTURES_DIR,
LV_EXPLORER_VIDEO_DIR,
LV_EXPLORER_DOCS_DIR,
LV_EXPLORER_FS_DIR,
} lv_file_explorer_dir_t;
#endif
/*Data of canvas*/
typedef struct {
lv_obj_t obj;
lv_obj_t * cont;
lv_obj_t * head_area;
lv_obj_t * browser_area;
lv_obj_t * file_table;
lv_obj_t * path_label;
#if LV_FILE_EXPLORER_QUICK_ACCESS
lv_obj_t * quick_access_area;
lv_obj_t * list_device;
lv_obj_t * list_places;
char * home_dir;
char * music_dir;
char * pictures_dir;
char * video_dir;
char * docs_dir;
char * fs_dir;
#endif
const char * sel_fn;
char current_path[LV_FILE_EXPLORER_PATH_MAX_LEN];
lv_file_explorer_sort_t sort;
} lv_file_explorer_t;
extern const lv_obj_class_t lv_file_explorer_class;
/***********************
* GLOBAL VARIABLES
***********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
lv_obj_t * lv_file_explorer_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
#if LV_FILE_EXPLORER_QUICK_ACCESS
/**
* Set file_explorer
* @param obj pointer to a label object
* @param dir the dir from 'lv_file_explorer_dir_t' enum.
* @param path path
*/
void lv_file_explorer_set_quick_access_path(lv_obj_t * obj, lv_file_explorer_dir_t dir, const char * path);
#endif
/**
* Set file_explorer sort
* @param obj pointer to a file explorer object
* @param sort the sort from 'lv_file_explorer_sort_t' enum.
*/
void lv_file_explorer_set_sort(lv_obj_t * obj, lv_file_explorer_sort_t sort);
/*=====================
* Getter functions
*====================*/
/**
* Get file explorer Selected file
* @param obj pointer to a file explorer object
* @return pointer to the file explorer selected file name
*/
const char * lv_file_explorer_get_selected_file_name(const lv_obj_t * obj);
/**
* Get file explorer cur path
* @param obj pointer to a file explorer object
* @return pointer to the file explorer cur path
*/
const char * lv_file_explorer_get_current_path(const lv_obj_t * obj);
/**
* Get file explorer head area obj
* @param obj pointer to a file explorer object
* @return pointer to the file explorer head area obj(lv_obj)
*/
lv_obj_t * lv_file_explorer_get_header(lv_obj_t * obj);
/**
* Get file explorer head area obj
* @param obj pointer to a file explorer object
* @return pointer to the file explorer quick access area obj(lv_obj)
*/
lv_obj_t * lv_file_explorer_get_quick_access_area(lv_obj_t * obj);
/**
* Get file explorer path obj(label)
* @param obj pointer to a file explorer object
* @return pointer to the file explorer path obj(lv_label)
*/
lv_obj_t * lv_file_explorer_get_path_label(lv_obj_t * obj);
#if LV_FILE_EXPLORER_QUICK_ACCESS
/**
* Get file explorer places list obj(lv_list)
* @param obj pointer to a file explorer object
* @return pointer to the file explorer places list obj(lv_list)
*/
lv_obj_t * lv_file_explorer_get_places_list(lv_obj_t * obj);
/**
* Get file explorer device list obj(lv_list)
* @param obj pointer to a file explorer object
* @return pointer to the file explorer device list obj(lv_list)
*/
lv_obj_t * lv_file_explorer_get_device_list(lv_obj_t * obj);
#endif
/**
* Get file explorer file list obj(lv_table)
* @param obj pointer to a file explorer object
* @return pointer to the file explorer file table obj(lv_table)
*/
lv_obj_t * lv_file_explorer_get_file_table(lv_obj_t * obj);
/**
* Set file_explorer sort
* @param obj pointer to a file explorer object
* @return the current mode from 'lv_file_explorer_sort_t'
*/
lv_file_explorer_sort_t lv_file_explorer_get_sort(const lv_obj_t * obj);
/*=====================
* Other functions
*====================*/
/**
* Open a specified path
* @param obj pointer to a file explorer object
* @param dir pointer to the path
*/
void lv_file_explorer_open_dir(lv_obj_t * obj, const char * dir);
/**********************
* MACROS
**********************/
#endif /*LV_USE_FILE_EXPLORER*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_FILE_EXPLORER_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/monkey/lv_monkey.c | /**
* @file lv_monkey.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_monkey.h"
#if LV_USE_MONKEY != 0
/*********************
* DEFINES
*********************/
#define MONKEY_PERIOD_RANGE_MIN_DEF 100
#define MONKEY_PERIOD_RANGE_MAX_DEF 1000
/**********************
* TYPEDEFS
**********************/
struct _lv_monkey {
lv_monkey_config_t config;
lv_indev_data_t indev_data;
lv_indev_t * indev;
lv_timer_t * timer;
void * user_data;
};
static const lv_key_t lv_key_map[] = {
LV_KEY_UP,
LV_KEY_DOWN,
LV_KEY_RIGHT,
LV_KEY_LEFT,
LV_KEY_ESC,
LV_KEY_DEL,
LV_KEY_BACKSPACE,
LV_KEY_ENTER,
LV_KEY_NEXT,
LV_KEY_PREV,
LV_KEY_HOME,
LV_KEY_END,
};
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_monkey_read_cb(lv_indev_t * indev, lv_indev_data_t * data);
static int32_t lv_monkey_random(int32_t howsmall, int32_t howbig);
static void lv_monkey_timer_cb(lv_timer_t * timer);
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_monkey_config_init(lv_monkey_config_t * config)
{
lv_memzero(config, sizeof(lv_monkey_config_t));
config->type = LV_INDEV_TYPE_POINTER;
config->period_range.min = MONKEY_PERIOD_RANGE_MIN_DEF;
config->period_range.max = MONKEY_PERIOD_RANGE_MAX_DEF;
}
lv_monkey_t * lv_monkey_create(const lv_monkey_config_t * config)
{
lv_monkey_t * monkey = lv_malloc(sizeof(lv_monkey_t));
LV_ASSERT_MALLOC(monkey);
lv_memzero(monkey, sizeof(lv_monkey_t));
monkey->config = *config;
monkey->timer = lv_timer_create(lv_monkey_timer_cb, monkey->config.period_range.min, monkey);
lv_timer_pause(monkey->timer);
monkey->indev = lv_indev_create();
lv_indev_set_type(monkey->indev, config->type);
lv_indev_set_read_cb(monkey->indev, lv_monkey_read_cb);
lv_indev_set_user_data(monkey->indev, monkey);
return monkey;
}
lv_indev_t * lv_monkey_get_indev(lv_monkey_t * monkey)
{
LV_ASSERT_NULL(monkey);
return monkey->indev;
}
void lv_monkey_set_enable(lv_monkey_t * monkey, bool en)
{
LV_ASSERT_NULL(monkey);
en ? lv_timer_resume(monkey->timer) : lv_timer_pause(monkey->timer);
}
bool lv_monkey_get_enable(lv_monkey_t * monkey)
{
LV_ASSERT_NULL(monkey);
return !monkey->timer->paused;
}
void lv_monkey_set_user_data(lv_monkey_t * monkey, void * user_data)
{
LV_ASSERT_NULL(monkey);
monkey->user_data = user_data;
}
void * lv_monkey_get_user_data(lv_monkey_t * monkey)
{
LV_ASSERT_NULL(monkey);
return monkey->user_data;
}
void lv_monkey_delete(lv_monkey_t * monkey)
{
LV_ASSERT_NULL(monkey);
lv_timer_delete(monkey->timer);
lv_indev_delete(monkey->indev);
lv_free(monkey);
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_monkey_read_cb(lv_indev_t * indev, lv_indev_data_t * data)
{
lv_monkey_t * monkey = lv_indev_get_user_data(indev);
data->btn_id = monkey->indev_data.btn_id;
data->point = monkey->indev_data.point;
data->enc_diff = monkey->indev_data.enc_diff;
data->state = monkey->indev_data.state;
}
static int32_t lv_monkey_random(int32_t howsmall, int32_t howbig)
{
if(howsmall >= howbig) {
return howsmall;
}
int32_t diff = howbig - howsmall;
return (int32_t)lv_rand(0, diff) + howsmall;
}
static void lv_monkey_timer_cb(lv_timer_t * timer)
{
lv_monkey_t * monkey = timer->user_data;
lv_indev_data_t * data = &monkey->indev_data;
switch(lv_indev_get_type(monkey->indev)) {
case LV_INDEV_TYPE_POINTER:
data->point.x = (int32_t)lv_monkey_random(0, LV_HOR_RES - 1);
data->point.y = (int32_t)lv_monkey_random(0, LV_VER_RES - 1);
break;
case LV_INDEV_TYPE_ENCODER:
data->enc_diff = (int16_t)lv_monkey_random(monkey->config.input_range.min, monkey->config.input_range.max);
break;
case LV_INDEV_TYPE_BUTTON:
data->btn_id = (uint32_t)lv_monkey_random(monkey->config.input_range.min, monkey->config.input_range.max);
break;
case LV_INDEV_TYPE_KEYPAD: {
int32_t index = lv_monkey_random(0, sizeof(lv_key_map) / sizeof(lv_key_map[0]) - 1);
data->key = lv_key_map[index];
break;
}
default:
break;
}
data->state = lv_monkey_random(0, 100) < 50 ? LV_INDEV_STATE_RELEASED : LV_INDEV_STATE_PRESSED;
lv_timer_set_period(monkey->timer, lv_monkey_random(monkey->config.period_range.min, monkey->config.period_range.max));
}
#endif /*LV_USE_MONKEY*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/monkey/lv_monkey.h | /**
* @file lv_monkey.h
*
*/
#ifndef LV_MONKEY_H
#define LV_MONKEY_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_MONKEY != 0
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
struct _lv_monkey;
typedef struct _lv_monkey lv_monkey_t;
typedef struct {
/**< Input device type*/
lv_indev_type_t type;
/**< Monkey execution period*/
struct {
//! @cond Doxygen_Suppress
uint32_t min;
uint32_t max;
//! @endcond
} period_range;
/**< The range of input value*/
struct {
int32_t min;
int32_t max;
} input_range;
} lv_monkey_config_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Initialize a monkey config with default values
* @param config pointer to 'lv_monkey_config_t' variable to initialize
*/
void lv_monkey_config_init(lv_monkey_config_t * config);
/**
* Create monkey for test
* @param config pointer to 'lv_monkey_config_t' variable
* @return pointer to the created monkey
*/
lv_monkey_t * lv_monkey_create(const lv_monkey_config_t * config);
/**
* Get monkey input device
* @param monkey pointer to a monkey
* @return pointer to the input device
*/
lv_indev_t * lv_monkey_get_indev(lv_monkey_t * monkey);
/**
* Enable monkey
* @param monkey pointer to a monkey
* @param en set to true to enable
*/
void lv_monkey_set_enable(lv_monkey_t * monkey, bool en);
/**
* Get whether monkey is enabled
* @param monkey pointer to a monkey
* @return return true if monkey enabled
*/
bool lv_monkey_get_enable(lv_monkey_t * monkey);
/**
* Set the user_data field of the monkey
* @param monkey pointer to a monkey
* @param user_data pointer to the new user_data.
*/
void lv_monkey_set_user_data(lv_monkey_t * monkey, void * user_data);
/**
* Get the user_data field of the monkey
* @param monkey pointer to a monkey
* @return the pointer to the user_data of the monkey
*/
void * lv_monkey_get_user_data(lv_monkey_t * monkey);
/**
* Delete monkey
* @param monkey pointer to monkey
*/
void lv_monkey_delete(lv_monkey_t * monkey);
/**********************
* MACROS
**********************/
#endif /*LV_USE_MONKEY*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_MONKEY_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/observer/lv_observer.c | /**
* @file lv_observer.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_observer.h"
#if LV_USE_OBSERVER
#include "../../lvgl.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
uint32_t flag;
lv_subject_value_t value;
uint32_t inv : 1;
} flag_and_cond_t;
/**********************
* STATIC PROTOTYPES
**********************/
static void unsubscribe_on_delete_cb(lv_event_t * e);
static void group_notify_cb(lv_subject_t * subject, lv_observer_t * observer);
static lv_observer_t * bind_to_bitfield(lv_subject_t * subject, lv_obj_t * obj, lv_observer_cb_t cb, uint32_t flag,
int32_t ref_value, bool inv);
static void obj_flag_observer_cb(lv_subject_t * subject, lv_observer_t * observer);
static void obj_state_observer_cb(lv_subject_t * subject, lv_observer_t * observer);
static void btn_value_changed_event_cb(lv_event_t * e);
static void label_text_observer_cb(lv_subject_t * subject, lv_observer_t * observer);
static void arc_value_changed_event_cb(lv_event_t * e);
static void arc_value_observer_cb(lv_subject_t * subject, lv_observer_t * observer);
static void slider_value_changed_event_cb(lv_event_t * e);
static void slider_value_observer_cb(lv_subject_t * subject, lv_observer_t * observer);
static void roller_value_changed_event_cb(lv_event_t * e);
static void roller_value_observer_cb(lv_subject_t * subject, lv_observer_t * observer);
static void dropdown_value_changed_event_cb(lv_event_t * e);
static void dropdown_value_observer_cb(lv_subject_t * subject, lv_observer_t * observer);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_subject_init_int(lv_subject_t * subject, int32_t value)
{
lv_memzero(subject, sizeof(lv_subject_t));
subject->type = LV_SUBJECT_TYPE_INT;
subject->value.num = value;
subject->prev_value.num = value;
_lv_ll_init(&(subject->subs_ll), sizeof(lv_observer_t));
}
void lv_subject_set_int(lv_subject_t * subject, int32_t value)
{
if(subject->type != LV_SUBJECT_TYPE_INT) {
LV_LOG_WARN("Subject type is not LV_SUBJECT_TYPE_INT");
return;
}
subject->prev_value.num = subject->value.num;
subject->value.num = value;
lv_subject_notify(subject);
}
int32_t lv_subject_get_int(lv_subject_t * subject)
{
if(subject->type != LV_SUBJECT_TYPE_INT) {
LV_LOG_WARN("Subject type is not LV_SUBJECT_TYPE_INT");
return 0;
}
return subject->value.num;
}
int32_t lv_subject_get_previous_int(lv_subject_t * subject)
{
if(subject->type != LV_SUBJECT_TYPE_INT) {
LV_LOG_WARN("Subject type is not LV_SUBJECT_TYPE_INT");
return 0;
}
return subject->prev_value.num;
}
void lv_subject_init_string(lv_subject_t * subject, char * buf, char * prev_buf, size_t size, const char * value)
{
lv_memzero(subject, sizeof(lv_subject_t));
lv_strncpy(buf, value, size);
if(prev_buf) lv_strncpy(prev_buf, value, size);
subject->type = LV_SUBJECT_TYPE_STRING;
subject->size = size;
subject->value.pointer = buf;
subject->prev_value.pointer = prev_buf;
_lv_ll_init(&(subject->subs_ll), sizeof(lv_observer_t));
}
void lv_subject_copy_string(lv_subject_t * subject, const char * buf)
{
if(subject->type != LV_SUBJECT_TYPE_STRING) {
LV_LOG_WARN("Subject type is not LV_SUBJECT_TYPE_INT");
return;
}
if(subject->size < 1) return;
if(subject->prev_value.pointer) {
lv_strncpy((char *)subject->prev_value.pointer, subject->value.pointer, subject->size - 1);
}
lv_strncpy((char *)subject->value.pointer, buf, subject->size - 1);
lv_subject_notify(subject);
}
const char * lv_subject_get_string(lv_subject_t * subject)
{
if(subject->type != LV_SUBJECT_TYPE_STRING) {
LV_LOG_WARN("Subject type is not LV_SUBJECT_TYPE_STRING");
return "";
}
return subject->value.pointer;
}
const char * lv_subject_get_previous_string(lv_subject_t * subject)
{
if(subject->type != LV_SUBJECT_TYPE_STRING) {
LV_LOG_WARN("Subject type is not LV_SUBJECT_TYPE_STRING");
return NULL;
}
return subject->prev_value.pointer;
}
void lv_subject_init_pointer(lv_subject_t * subject, void * value)
{
lv_memzero(subject, sizeof(lv_subject_t));
subject->type = LV_SUBJECT_TYPE_POINTER;
subject->value.pointer = value;
subject->prev_value.pointer = value;
_lv_ll_init(&(subject->subs_ll), sizeof(lv_observer_t));
}
void lv_subject_set_pointer(lv_subject_t * subject, void * ptr)
{
if(subject->type != LV_SUBJECT_TYPE_POINTER) {
LV_LOG_WARN("Subject type is not LV_SUBJECT_TYPE_POINTER");
return;
}
subject->prev_value.pointer = subject->value.pointer;
subject->value.pointer = ptr;
lv_subject_notify(subject);
}
const void * lv_subject_get_pointer(lv_subject_t * subject)
{
if(subject->type != LV_SUBJECT_TYPE_POINTER) {
LV_LOG_WARN("Subject type is not LV_SUBJECT_TYPE_POINTER");
return NULL;
}
return subject->value.pointer;
}
const void * lv_subject_get_previous_pointer(lv_subject_t * subject)
{
if(subject->type != LV_SUBJECT_TYPE_POINTER) {
LV_LOG_WARN("Subject type is not LV_SUBJECT_TYPE_POINTER");
return NULL;
}
return subject->prev_value.pointer;
}
void lv_subject_init_color(lv_subject_t * subject, lv_color_t color)
{
lv_memzero(subject, sizeof(lv_subject_t));
subject->type = LV_SUBJECT_TYPE_COLOR;
subject->value.color = color;
subject->prev_value.color = color;
_lv_ll_init(&(subject->subs_ll), sizeof(lv_observer_t));
}
void lv_subject_set_color(lv_subject_t * subject, lv_color_t color)
{
if(subject->type != LV_SUBJECT_TYPE_COLOR) {
LV_LOG_WARN("Subject type is not LV_SUBJECT_TYPE_COLOR");
return;
}
subject->prev_value.color = subject->value.color;
subject->value.color = color;
lv_subject_notify(subject);
}
lv_color_t lv_subject_get_color(lv_subject_t * subject)
{
if(subject->type != LV_SUBJECT_TYPE_COLOR) {
LV_LOG_WARN("Subject type is not LV_SUBJECT_TYPE_COLOR");
return lv_color_black();
}
return subject->value.color;
}
lv_color_t lv_subject_get_previous_color(lv_subject_t * subject)
{
if(subject->type != LV_SUBJECT_TYPE_COLOR) {
LV_LOG_WARN("Subject type is not LV_SUBJECT_TYPE_COLOR");
return lv_color_black();
}
return subject->prev_value.color;
}
void lv_subject_init_group(lv_subject_t * subject, lv_subject_t * list[], uint32_t list_len)
{
subject->type = LV_SUBJECT_TYPE_GROUP;
subject->size = list_len;
_lv_ll_init(&(subject->subs_ll), sizeof(lv_observer_t));
subject->value.pointer = list;
/* bind all subjects to this subject */
uint32_t i;
for(i = 0; i < list_len; i++) {
/*If a subject in the group changes notify the group itself*/
lv_subject_add_observer(list[i], group_notify_cb, subject);
}
}
lv_subject_t * lv_subject_get_group_element(lv_subject_t * subject, int32_t index)
{
if(subject->type != LV_SUBJECT_TYPE_GROUP) {
LV_LOG_WARN("Subject type is not LV_SUBJECT_TYPE_GROUP");
return NULL;
}
if(index >= subject->size) return NULL;
return ((lv_subject_t **)(subject->value.pointer))[index];
}
lv_observer_t * lv_subject_add_observer(lv_subject_t * subject, lv_observer_cb_t cb, void * user_data)
{
lv_observer_t * observer = lv_subject_add_observer_obj(subject, cb, NULL, user_data);
return observer;
}
lv_observer_t * lv_subject_add_observer_obj(lv_subject_t * subject, lv_observer_cb_t cb, lv_obj_t * obj,
void * user_data)
{
lv_observer_t * observer = _lv_ll_ins_tail(&(subject->subs_ll));
LV_ASSERT_MALLOC(observer);
if(observer == NULL) return NULL;
lv_memzero(observer, sizeof(*observer));
observer->subject = subject;
observer->cb = cb;
observer->user_data = user_data;
observer->target = obj;
/* subscribe to delete event of the object */
if(obj != NULL) {
lv_obj_add_event(obj, unsubscribe_on_delete_cb, LV_EVENT_DELETE, observer);
}
/* update object immediately */
if(observer->cb) observer->cb(subject, observer);
return observer;
}
lv_observer_t * lv_subject_add_observer_with_target(lv_subject_t * subject, lv_observer_cb_t cb, void * target,
void * user_data)
{
lv_observer_t * observer = _lv_ll_ins_tail(&(subject->subs_ll));
LV_ASSERT_MALLOC(observer);
if(observer == NULL) return NULL;
lv_memzero(observer, sizeof(*observer));
observer->subject = subject;
observer->cb = cb;
observer->user_data = user_data;
observer->target = target;
/* update object immediately */
if(observer->cb) observer->cb(subject, observer);
return observer;
}
void lv_observer_remove(lv_observer_t * observer)
{
LV_ASSERT_NULL(observer);
observer->subject->notify_restart_query = 1;
_lv_ll_remove(&(observer->subject->subs_ll), observer);
if(observer->auto_free_user_data) {
lv_free(observer->user_data);
}
lv_free(observer);
}
void lv_subject_remove_all_obj(lv_subject_t * subject, lv_obj_t * obj)
{
while(lv_obj_remove_event_cb(obj, unsubscribe_on_delete_cb));
while(lv_obj_remove_event_cb(obj, btn_value_changed_event_cb));
while(lv_obj_remove_event_cb(obj, arc_value_changed_event_cb));
while(lv_obj_remove_event_cb(obj, roller_value_changed_event_cb));
while(lv_obj_remove_event_cb(obj, dropdown_value_changed_event_cb));
lv_observer_t * observer = _lv_ll_get_head(&subject->subs_ll);
while(observer) {
lv_observer_t * observer_next = _lv_ll_get_next(&subject->subs_ll, observer);
if(observer->target == obj) {
lv_observer_remove(observer);
}
observer = observer_next;
}
}
void * lv_observer_get_target(lv_observer_t * observer)
{
LV_ASSERT_NULL(observer);
return observer->target;
}
void lv_subject_notify(lv_subject_t * subject)
{
LV_ASSERT_NULL(subject);
lv_observer_t * observer;
_LV_LL_READ(&(subject->subs_ll), observer) {
observer->notified = 0;
}
do {
subject->notify_restart_query = 0;
_LV_LL_READ(&(subject->subs_ll), observer) {
if(observer->cb && observer->notified == 0) {
observer->cb(subject, observer);
if(subject->notify_restart_query) break;
observer->notified = 1;
}
}
} while(subject->notify_restart_query);
}
lv_observer_t * lv_obj_bind_flag_if_eq(lv_obj_t * obj, lv_subject_t * subject, lv_obj_flag_t flag, int32_t ref_value)
{
lv_observer_t * observable = bind_to_bitfield(subject, obj, obj_flag_observer_cb, flag, ref_value, false);
return observable;
}
lv_observer_t * lv_obj_bind_flag_if_not_eq(lv_obj_t * obj, lv_subject_t * subject, lv_obj_flag_t flag,
int32_t ref_value)
{
lv_observer_t * observable = bind_to_bitfield(subject, obj, obj_flag_observer_cb, flag, ref_value, true);
return observable;
}
lv_observer_t * lv_obj_bind_state_if_eq(lv_obj_t * obj, lv_subject_t * subject, lv_state_t state, int32_t ref_value)
{
lv_observer_t * observable = bind_to_bitfield(subject, obj, obj_state_observer_cb, state, ref_value, false);
return observable;
}
lv_observer_t * lv_obj_bind_state_if_not_eq(lv_obj_t * obj, lv_subject_t * subject, lv_state_t state, int32_t ref_value)
{
lv_observer_t * observable = bind_to_bitfield(subject, obj, obj_state_observer_cb, state, ref_value, true);
return observable;
}
lv_observer_t * lv_button_bind_checked(lv_obj_t * obj, lv_subject_t * subject)
{
lv_observer_t * observable = bind_to_bitfield(subject, obj, obj_state_observer_cb, LV_STATE_CHECKED, 1, false);
lv_obj_add_event(obj, btn_value_changed_event_cb, LV_EVENT_VALUE_CHANGED, subject);
return observable;
}
lv_observer_t * lv_label_bind_text(lv_obj_t * obj, lv_subject_t * subject, const char * fmt)
{
if(fmt == NULL) {
if(subject->type != LV_SUBJECT_TYPE_STRING && subject->type != LV_SUBJECT_TYPE_POINTER) {
LV_LOG_WARN("Incompatible subject type: %d", subject->type);
return NULL;
}
}
else {
if(subject->type != LV_SUBJECT_TYPE_STRING && subject->type != LV_SUBJECT_TYPE_POINTER &&
subject->type != LV_SUBJECT_TYPE_INT) {
LV_LOG_WARN("Incompatible subject type: %d", subject->type);
return NULL;
}
}
lv_observer_t * observer = lv_subject_add_observer_obj(subject, label_text_observer_cb, obj, (void *)fmt);
return observer;
}
lv_observer_t * lv_arc_bind_value(lv_obj_t * obj, lv_subject_t * subject)
{
if(subject->type != LV_SUBJECT_TYPE_INT) {
LV_LOG_WARN("Incompatible subject type: %d", subject->type);
return NULL;
}
lv_obj_add_event(obj, arc_value_changed_event_cb, LV_EVENT_VALUE_CHANGED, subject);
lv_observer_t * observer = lv_subject_add_observer_obj(subject, arc_value_observer_cb, obj, NULL);
return observer;
}
lv_observer_t * lv_slider_bind_value(lv_obj_t * obj, lv_subject_t * subject)
{
if(subject->type != LV_SUBJECT_TYPE_INT) {
LV_LOG_WARN("Incompatible subject type: %d", subject->type);
return NULL;
}
lv_obj_add_event(obj, slider_value_changed_event_cb, LV_EVENT_VALUE_CHANGED, subject);
lv_observer_t * observer = lv_subject_add_observer_obj(subject, slider_value_observer_cb, obj, NULL);
return observer;
}
lv_observer_t * lv_roller_bind_value(lv_obj_t * obj, lv_subject_t * subject)
{
if(subject->type != LV_SUBJECT_TYPE_INT) {
LV_LOG_WARN("Incompatible subject type: %d", subject->type);
return NULL;
}
lv_obj_add_event(obj, roller_value_changed_event_cb, LV_EVENT_VALUE_CHANGED, subject);
lv_observer_t * observer = lv_subject_add_observer_obj(subject, roller_value_observer_cb, obj, NULL);
return observer;
}
lv_observer_t * lv_dropdown_bind_value(lv_obj_t * obj, lv_subject_t * subject)
{
if(subject->type != LV_SUBJECT_TYPE_INT) {
LV_LOG_WARN("Incompatible subject type: %d", subject->type);
return NULL;
}
lv_obj_add_event(obj, dropdown_value_changed_event_cb, LV_EVENT_VALUE_CHANGED, subject);
lv_observer_t * observer = lv_subject_add_observer_obj(subject, dropdown_value_observer_cb, obj, NULL);
return observer;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void group_notify_cb(lv_subject_t * subject, lv_observer_t * observer)
{
LV_UNUSED(subject);
lv_subject_t * subject_group = observer->user_data;
lv_subject_notify(subject_group);
}
static void unsubscribe_on_delete_cb(lv_event_t * e)
{
lv_observer_t * observer = lv_event_get_user_data(e);
lv_observer_remove(observer);
}
static lv_observer_t * bind_to_bitfield(lv_subject_t * subject, lv_obj_t * obj, lv_observer_cb_t cb, uint32_t flag,
int32_t ref_value, bool inv)
{
if(subject->type != LV_SUBJECT_TYPE_INT) {
LV_LOG_WARN("Incompatible subject type: %d", subject->type);
return NULL;
}
flag_and_cond_t * p = lv_malloc(sizeof(flag_and_cond_t));
if(p == NULL) {
LV_LOG_WARN("Out of memory");
return NULL;
}
p->flag = flag;
p->value.num = ref_value;
p->inv = inv;
lv_observer_t * observable = lv_subject_add_observer_obj(subject, cb, obj, p);
observable->auto_free_user_data = 1;
return observable;
}
static void obj_flag_observer_cb(lv_subject_t * subject, lv_observer_t * observer)
{
flag_and_cond_t * p = observer->user_data;
bool res = subject->value.num == p->value.num;
if(p->inv) res = !res;
if(res) {
lv_obj_add_flag(observer->target, p->flag);
}
else {
lv_obj_remove_flag(observer->target, p->flag);
}
}
static void obj_state_observer_cb(lv_subject_t * subject, lv_observer_t * observer)
{
flag_and_cond_t * p = observer->user_data;
bool res = subject->value.num == p->value.num;
if(p->inv) res = !res;
if(res) {
lv_obj_add_state(observer->target, p->flag);
}
else {
lv_obj_remove_state(observer->target, p->flag);
}
}
static void btn_value_changed_event_cb(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_current_target(e);
lv_subject_t * subject = lv_event_get_user_data(e);
lv_subject_set_int(subject, lv_obj_has_state(obj, LV_STATE_CHECKED));
}
static void label_text_observer_cb(lv_subject_t * subject, lv_observer_t * observer)
{
const char * fmt = observer->user_data;
if(fmt == NULL) {
lv_label_set_text(observer->target, subject->value.pointer);
}
else {
switch(subject->type) {
case LV_SUBJECT_TYPE_INT:
lv_label_set_text_fmt(observer->target, fmt, subject->value.num);
break;
case LV_SUBJECT_TYPE_STRING:
case LV_SUBJECT_TYPE_POINTER:
lv_label_set_text_fmt(observer->target, fmt, subject->value.pointer);
break;
default:
break;
}
}
}
static void arc_value_changed_event_cb(lv_event_t * e)
{
lv_obj_t * arc = lv_event_get_current_target(e);
lv_subject_t * subject = lv_event_get_user_data(e);
lv_subject_set_int(subject, lv_arc_get_value(arc));
}
static void arc_value_observer_cb(lv_subject_t * subject, lv_observer_t * observer)
{
lv_arc_set_value(observer->target, subject->value.num);
}
static void slider_value_changed_event_cb(lv_event_t * e)
{
lv_obj_t * slider = lv_event_get_current_target(e);
lv_subject_t * subject = lv_event_get_user_data(e);
lv_subject_set_int(subject, lv_slider_get_value(slider));
}
static void slider_value_observer_cb(lv_subject_t * subject, lv_observer_t * observer)
{
lv_slider_set_value(observer->target, subject->value.num, LV_ANIM_OFF);
}
static void roller_value_changed_event_cb(lv_event_t * e)
{
lv_obj_t * roller = lv_event_get_current_target(e);
lv_subject_t * subject = lv_event_get_user_data(e);
lv_subject_set_int(subject, lv_roller_get_selected(roller));
}
static void roller_value_observer_cb(lv_subject_t * subject, lv_observer_t * observer)
{
if((int32_t)lv_roller_get_selected(observer->target) != subject->value.num) {
lv_roller_set_selected(observer->target, subject->value.num, LV_ANIM_OFF);
}
}
static void dropdown_value_changed_event_cb(lv_event_t * e)
{
lv_obj_t * dropdown = lv_event_get_current_target(e);
lv_subject_t * subject = lv_event_get_user_data(e);
lv_subject_set_int(subject, lv_dropdown_get_selected(dropdown));
}
static void dropdown_value_observer_cb(lv_subject_t * subject, lv_observer_t * observer)
{
lv_dropdown_set_selected(observer->target, subject->value.num);
}
#endif /*LV_USE_OBSERVER*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/observer/lv_observer.h | /**
* @file lv_observer.h
*
*/
#ifndef LV_OBSERVER_H
#define LV_OBSERVER_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../core/lv_obj.h"
#if LV_USE_OBSERVER
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
struct _lv_observer_t;
typedef enum {
LV_SUBJECT_TYPE_NONE = 0,
LV_SUBJECT_TYPE_INT = 1, /**< an int32_t*/
LV_SUBJECT_TYPE_POINTER = 2, /**< a void pointer*/
LV_SUBJECT_TYPE_COLOR = 3, /**< an lv_color_t*/
LV_SUBJECT_TYPE_GROUP = 4, /**< an array of subjects*/
LV_SUBJECT_TYPE_STRING = 5, /**< a char pointer*/
} lv_subject_type_t;
/**
* A common type to handle all the various observable types in the same way
*/
typedef union {
int32_t num; /**< Integer number (opacity, enums, booleans or "normal" numbers)*/
const void * pointer; /**< Constant pointer (string buffer, format string, font, cone text, etc)*/
lv_color_t color; /**< Color */
} lv_subject_value_t;
/**
* The subject (an observable value)
*/
typedef struct {
lv_ll_t subs_ll; /**< Subscribers*/
uint32_t type : 4;
uint32_t size : 28; /**< Might be used to store a size related to `type`*/
lv_subject_value_t value; /**< Actual value*/
lv_subject_value_t prev_value; /**< Previous value*/
uint32_t notify_restart_query : 1; /**< If an observer deleted start notifying from the beginning. */
} lv_subject_t;
/**
* Callback called when the observed value changes
* @param s the lv_observer_t object created when the object was subscribed to the value
*/
typedef void (*lv_observer_cb_t)(lv_subject_t * subject, struct _lv_observer_t * observer);
/**
* The observer object: a descriptor returned when subscribing LVGL widgets to subjects
*/
typedef struct _lv_observer_t {
lv_subject_t * subject; /**< The observed value */
lv_observer_cb_t cb; /**< Callback that should be called when the value changes*/
void * target; /**< A target for the observer, e.g. a widget or style*/
void * user_data; /**< Additional parameter supplied when subscribing*/
uint32_t auto_free_user_data : 1; /**< Automatically free user data when the observer is removed */
uint32_t notified : 1; /**< Mark if this observer was already notified*/
} lv_observer_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Initialize an integer type subject
* @param subject pointer to the subject
* @param value initial value
*/
void lv_subject_init_int(lv_subject_t * subject, int32_t value);
/**
* Set the value of an integer subject. It will notify all the observers as well.
* @param subject pointer to the subject
* @param value the new value
*/
void lv_subject_set_int(lv_subject_t * subject, int32_t value);
/**
* Get the current value of an integer subject
* @param subject pointer to the subject
* @return the current value
*/
int32_t lv_subject_get_int(lv_subject_t * subject);
/**
* Get the previous value of an integer subject
* @param subject pointer to the subject
* @return the current value
*/
int32_t lv_subject_get_previous_int(lv_subject_t * subject);
/**
* Initialize a string type subject
* @param subject pointer to the subject
* @param buf pointer to a buffer to store the string
* @param prev_buf pointer to a buffer to store the previous string, can be NULL if not used
* @param size size of the buffer
* @param value initial value as a string, e.g. "hello"
* @note the string subject stores the whole string, not only a pointer
*/
void lv_subject_init_string(lv_subject_t * subject, char * buf, char * prev_buf, size_t size, const char * value);
/**
* Copy a string to a subject. It will notify all the observers as well.
* @param subject pointer to the subject
* @param buf the new string
*/
void lv_subject_copy_string(lv_subject_t * subject, const char * buf);
/**
* Get the current value of an string subject
* @param subject pointer to the subject
* @return pointer to the buffer containing the current value
*/
const char * lv_subject_get_string(lv_subject_t * subject);
/**
* Get the previous value of an string subject
* @param subject pointer to the subject
* @return pointer to the buffer containing the current value
* @note NULL will be returned if NULL was passed in `lv_subject_init_string()`
* as `prev_buf`
*/
const char * lv_subject_get_previous_string(lv_subject_t * subject);
/**
* Initialize an pointer type subject
* @param subject pointer to the subject
* @param value initial value
*/
void lv_subject_init_pointer(lv_subject_t * subject, void * value);
/**
* Set the value of a pointer subject. It will notify all the observers as well.
* @param subject pointer to the subject
* @param value the new value
*/
void lv_subject_set_pointer(lv_subject_t * subject, void * ptr);
/**
* Get the current value of a pointer subject
* @param subject pointer to the subject
* @return the current value
*/
const void * lv_subject_get_pointer(lv_subject_t * subject);
/**
* Get the previous value of a pointer subject
* @param subject pointer to the subject
* @return the current value
*/
const void * lv_subject_get_previous_pointer(lv_subject_t * subject);
/**
* Initialize an color type subject
* @param subject pointer to the subject
* @param value initial value
*/
void lv_subject_init_color(lv_subject_t * subject, lv_color_t color);
/**
* Set the value of a color subject. It will notify all the observers as well.
* @param subject pointer to the subject
* @param value the new value
*/
void lv_subject_set_color(lv_subject_t * subject, lv_color_t color);
/**
* Get the current value of a color subject
* @param subject pointer to the subject
* @return the current value
*/
lv_color_t lv_subject_get_color(lv_subject_t * subject);
/**
* Get the previous value of a color subject
* @param subject pointer to the subject
* @return the current value
*/
lv_color_t lv_subject_get_previous_color(lv_subject_t * subject);
/**
* Initialize a subject group
* @param subject pointer to the subject
* @param list list of other subject addresses, any of these changes `subject` will be notified
* @param list_len number of elements in `list`
*/
void lv_subject_init_group(lv_subject_t * subject, lv_subject_t * list[], uint32_t list_len);
/**
* Get an element from the subject group's list
* @param subject pointer to the subject
* @param index index of the element to get
* @return pointer a subject from the list, or NULL if the index is out of bounds
*/
lv_subject_t * lv_subject_get_group_element(lv_subject_t * subject, int32_t index);
/**
* Add an observer to a subject. When the subject changes `observer_cb` will be called.
* @param subject pointer to the subject
* @param observer_cb the callback to call
* @param user_data optional user data
* @return pointer to the created observer
*/
lv_observer_t * lv_subject_add_observer(lv_subject_t * subject, lv_observer_cb_t observer_cb, void * user_data);
/**
* Add an observer to a subject for an object.
* When the object is deleted, it will be removed from the subject automatically.
* @param subject pointer to the subject
* @param observer_cb the callback to call
* @param obj pointer to an object
* @param user_data optional user data
* @return pointer to the created observer
*/
lv_observer_t * lv_subject_add_observer_obj(lv_subject_t * subject, lv_observer_cb_t observer_cb, lv_obj_t * obj,
void * user_data);
/**
* Add an observer to a subject and also save a target.
* @param subject pointer to the subject
* @param observer_cb the callback to call
* @param target pointer to any data
* @param user_data optional user data
* @return pointer to the created observer
*/
lv_observer_t * lv_subject_add_observer_with_target(lv_subject_t * subject, lv_observer_cb_t cb, void * target,
void * user_data);
/**
* Remove an observer from its subject
* @param observer pointer to an observer
*/
void lv_observer_remove(lv_observer_t * observer);
/**
* Remove all observers from their subject related to an object
* @param observer pointer to an observer
* @param obj pointer to an object
*/
void lv_subject_remove_all_obj(lv_subject_t * subject, lv_obj_t * obj);
/**
* Get the target of an observer
* @param observer pointer to an observer
* @return pointer to the saved target
*/
void * lv_observer_get_target(lv_observer_t * observer);
/**
* Notify all observers of subject
* @param subject pointer to a subject
*/
void lv_subject_notify(lv_subject_t * subject);
/**
* Set an object flag if an integer subject's value is equal to a reference value, clear the flag otherwise
* @param obj pointer to an object
* @param subject pointer to a subject
* @param flag a flag to set or clear (e.g. `LV_OBJ_FLAG_HIDDEN`)
* @param ref_value a reference value to compare the subject's value with
* @return pointer to the created observer
*/
lv_observer_t * lv_obj_bind_flag_if_eq(lv_obj_t * obj, lv_subject_t * subject, lv_obj_flag_t flag, int32_t ref_value);
/**
* Set an object flag if an integer subject's value is not equal to a reference value, clear the flag otherwise
* @param obj pointer to an object
* @param subject pointer to a subject
* @param flag a flag to set or clear (e.g. `LV_OBJ_FLAG_HIDDEN`)
* @param ref_value a reference value to compare the subject's value with
* @return pointer to the created observer
*/
lv_observer_t * lv_obj_bind_flag_if_not_eq(lv_obj_t * obj, lv_subject_t * subject, lv_obj_flag_t flag,
int32_t ref_value);
/**
* Set an object state if an integer subject's value is equal to a reference value, clear the flag otherwise
* @param obj pointer to an object
* @param subject pointer to a subject
* @param flag a state to set or clear (e.g. `LV_STATE_CHECKED`)
* @param ref_value a reference value to compare the subject's value with
* @return pointer to the created observer
*/
lv_observer_t * lv_obj_bind_state_if_eq(lv_obj_t * obj, lv_subject_t * subject, lv_state_t state, int32_t ref_value);
/**
* Set an object state if an integer subject's value is not equal to a reference value, clear the flag otherwise
* @param obj pointer to an object
* @param subject pointer to a subject
* @param flag a state to set or clear (e.g. `LV_STATE_CHECKED`)
* @param ref_value a reference value to compare the subject's value with
* @return pointer to the created observer
*/
lv_observer_t * lv_obj_bind_state_if_not_eq(lv_obj_t * obj, lv_subject_t * subject, lv_state_t state,
int32_t ref_value);
/**
* Set an integer subject to 1 when a button is checked and set it 0 when unchecked.
* @param obj pointer to a button
* @param subject pointer to a subject
* @return pointer to the created observer
*/
lv_observer_t * lv_button_bind_checked(lv_obj_t * obj, lv_subject_t * subject);
/**
* Bind an integer, string, or pointer subject to a label.
* @param obj pointer to a label
* @param subject pointer to a subject
* @param fmt an optional format string with 1 format specifier (e.g. "%d °C")
* or NULL to bind the value directly.
* @return pointer to the created observer
* @note fmt == NULL can be used only with string and pointer subjects.
* @note if the subject is a pointer must point to a `\0` terminated string.
*/
lv_observer_t * lv_label_bind_text(lv_obj_t * obj, lv_subject_t * subject, const char * fmt);
/**
* Bind an integer subject to an arc's value
* @param obj pointer to an arc
* @param subject pointer to a subject
* @return pointer to the created observer
*/
lv_observer_t * lv_arc_bind_value(lv_obj_t * obj, lv_subject_t * subject);
/**
* Bind an integer subject to a slider's value
* @param obj pointer to a slider
* @param subject pointer to a subject
* @return pointer to the created observer
*/
lv_observer_t * lv_slider_bind_value(lv_obj_t * obj, lv_subject_t * subject);
/**
* Bind an integer subject to a roller's value
* @param obj pointer to a roller
* @param subject pointer to a subject
* @return pointer to the created observer
*/
lv_observer_t * lv_roller_bind_value(lv_obj_t * obj, lv_subject_t * subject);
/**
* Bind an integer subject to a dropdown's value
* @param obj pointer to a drop down
* @param subject pointer to a subject
* @return pointer to the created observer
*/
lv_observer_t * lv_dropdown_bind_value(lv_obj_t * obj, lv_subject_t * subject);
/**********************
* MACROS
**********************/
#endif /*LV_USE_OBSERVER*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_OBSERVER_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/sysmon/lv_sysmon.h | /**
* @file lv_sysmon.h
*
*/
#ifndef LV_SYSMON_H
#define LV_SYSMON_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../misc/lv_timer.h"
#include "../../others/observer/lv_observer.h"
#if LV_USE_SYSMON
#if LV_USE_LABEL == 0
#error "lv_sysmon: lv_label is required. Enable it in lv_conf.h (LV_USE_LABEL 1) "
#endif
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_subject_t subject;
lv_timer_t * timer;
} lv_sysmon_backend_data_t;
#if LV_USE_PERF_MONITOR
typedef struct {
struct {
uint32_t refr_start;
uint32_t refr_interval_sum;
uint32_t refr_elaps_sum;
uint32_t refr_cnt;
uint32_t render_start;
uint32_t render_elaps_sum;
uint32_t render_cnt;
uint32_t flush_start;
uint32_t flush_elaps_sum;
uint32_t flush_cnt;
} measured;
struct {
uint32_t fps;
uint32_t cpu;
uint32_t refr_avg_time;
uint32_t render_avg_time;
uint32_t flush_avg_time;
uint32_t render_real_avg_time;
} calculated;
} lv_sysmon_perf_info_t;
#endif
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a system monitor object.
* @param parent pointer to an object, it will be the parent of the new system monitor
* @return pointer to the new system monitor object
*/
lv_obj_t * lv_sysmon_create(lv_obj_t * parent);
/**
* Set the refresh period of the system monitor object
* @param obj pointer to a system monitor object
* @param period the refresh period in milliseconds
*/
void lv_sysmon_set_refr_period(lv_obj_t * obj, uint32_t period);
/**
* Initialize built-in system monitor, such as performance and memory monitor.
*/
void _lv_sysmon_builtin_init(void);
/**
* DeInitialize built-in system monitor, such as performance and memory monitor.
*/
void _lv_sysmon_builtin_deinit(void);
/**********************
* MACROS
**********************/
#else
#if LV_USE_PERF_MONITOR || LV_USE_MEM_MONITOR
#warning "lv_sysmon: lv_sysmon is required. Enable it in lv_conf.h (LV_USE_SYSMON 1)"
#endif
#endif /*LV_USE_SYSMON*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_SYSMON_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others | repos/zig_workbench/BaseLVGL/lib/lvgl/src/others/sysmon/lv_sysmon.c | /**
* @file lv_sysmon.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_sysmon.h"
#if LV_USE_SYSMON
#include "../../core/lv_global.h"
#include "../../misc/lv_async.h"
#include "../../stdlib/lv_string.h"
#include "../../widgets/label/lv_label.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_sysmon_class
#define SYSMON_REFR_PERIOD_DEF 300 /* ms */
#if LV_USE_PERF_MONITOR
#define sysmon_perf LV_GLOBAL_DEFAULT()->sysmon_perf
#endif
#if LV_USE_MEM_MONITOR
#define sysmon_mem LV_GLOBAL_DEFAULT()->sysmon_mem
#endif
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void sysmon_backend_init_async_cb(void * user_data);
#if LV_USE_PERF_MONITOR
static void perf_update_timer_cb(lv_timer_t * t);
static void perf_observer_cb(lv_subject_t * subject, lv_observer_t * observer);
#endif
#if LV_USE_MEM_MONITOR
static void mem_update_timer_cb(lv_timer_t * t);
static void mem_observer_cb(lv_subject_t * subject, lv_observer_t * observer);
#endif
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void _lv_sysmon_builtin_init(void)
{
#if LV_USE_PERF_MONITOR
static lv_sysmon_perf_info_t perf_info;
lv_subject_init_pointer(&sysmon_perf.subject, &perf_info);
sysmon_perf.timer = lv_timer_create(perf_update_timer_cb, SYSMON_REFR_PERIOD_DEF, &perf_info);
#endif
#if LV_USE_MEM_MONITOR
static lv_mem_monitor_t mem_info;
lv_subject_init_pointer(&sysmon_mem.subject, &mem_info);
sysmon_perf.timer = lv_timer_create(mem_update_timer_cb, SYSMON_REFR_PERIOD_DEF, &mem_info);
#endif
lv_async_call(sysmon_backend_init_async_cb, NULL);
}
void _lv_sysmon_builtin_deinit(void)
{
lv_async_call_cancel(sysmon_backend_init_async_cb, NULL);
#if LV_USE_PERF_MONITOR
// lv_subject_deinit(&sysmon_perf->subject);
lv_timer_delete(sysmon_perf.timer);
#endif
}
lv_obj_t * lv_sysmon_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * label = lv_label_create(parent);
lv_obj_set_style_bg_opa(label, LV_OPA_50, 0);
lv_obj_set_style_bg_color(label, lv_color_black(), 0);
lv_obj_set_style_text_color(label, lv_color_white(), 0);
lv_obj_set_style_pad_all(label, 3, 0);
lv_label_set_text(label, "?");
return label;
}
/**********************
* STATIC FUNCTIONS
**********************/
#if LV_USE_PERF_MONITOR
static void perf_monitor_disp_event_cb(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_sysmon_perf_info_t * info = (lv_sysmon_perf_info_t *)lv_subject_get_pointer(&sysmon_perf.subject);
switch(code) {
case LV_EVENT_REFR_START:
info->measured.refr_interval_sum += lv_tick_elaps(info->measured.refr_start);
info->measured.refr_start = lv_tick_get();
break;
case LV_EVENT_REFR_FINISH:
info->measured.refr_elaps_sum += lv_tick_elaps(info->measured.refr_start);
info->measured.refr_cnt++;
break;
case LV_EVENT_RENDER_START:
info->measured.render_start = lv_tick_get();
break;
case LV_EVENT_RENDER_READY:
info->measured.render_elaps_sum += lv_tick_elaps(info->measured.render_start);
info->measured.render_cnt++;
break;
case LV_EVENT_FLUSH_START:
info->measured.flush_start = lv_tick_get();
break;
case LV_EVENT_FLUSH_FINISH:
info->measured.flush_elaps_sum += lv_tick_elaps(info->measured.flush_start);
info->measured.flush_cnt++;
break;
default:
break;
}
}
static void perf_update_timer_cb(lv_timer_t * t)
{
lv_sysmon_perf_info_t * info = lv_timer_get_user_data(t);
info->calculated.fps = info->measured.refr_interval_sum ? (1000 * info->measured.refr_cnt /
info->measured.refr_interval_sum) : 0;
info->calculated.cpu = 100 - lv_timer_get_idle();
info->calculated.refr_avg_time = info->measured.refr_cnt ? (info->measured.refr_elaps_sum / info->measured.refr_cnt) :
0;
info->calculated.render_avg_time = info->measured.render_cnt ? (info->measured.render_elaps_sum /
info->measured.render_cnt) : 0;
info->calculated.flush_avg_time = info->measured.flush_cnt ? (info->measured.flush_elaps_sum / info->measured.flush_cnt)
: 0;
info->calculated.render_real_avg_time = info->calculated.render_avg_time - info->calculated.flush_avg_time;
lv_subject_set_pointer(&sysmon_perf.subject, info);
uint32_t refr_start = info->measured.refr_start;
lv_memzero(info, sizeof(lv_sysmon_perf_info_t));
info->measured.refr_start = refr_start;
}
static void perf_observer_cb(lv_subject_t * subject, lv_observer_t * observer)
{
lv_obj_t * label = lv_observer_get_target(observer);
const lv_sysmon_perf_info_t * perf = lv_subject_get_pointer(subject);
#if LV_USE_PERF_MONITOR_LOG_MODE
LV_LOG("sysmon: "
"%" LV_PRIu32 " FPS (refr_cnt: %" LV_PRIu32 " | redraw_cnt: %" LV_PRIu32 " | flush_cnt: %" LV_PRIu32 "), "
"refr %" LV_PRIu32 "ms (render %" LV_PRIu32 "ms | flush %" LV_PRIu32 "ms), "
"CPU %" LV_PRIu32 "%%\n",
perf->calculated.fps, perf->measured.refr_cnt, perf->measured.render_cnt, perf->measured.flush_cnt,
perf->calculated.refr_avg_time, perf->calculated.render_real_avg_time, perf->calculated.flush_avg_time,
perf->calculated.cpu);
#else
lv_label_set_text_fmt(
label,
"%" LV_PRIu32" FPS, %" LV_PRIu32 "%% CPU\n"
"%" LV_PRIu32" ms (%" LV_PRIu32" | %" LV_PRIu32")",
perf->calculated.fps, perf->calculated.cpu,
perf->calculated.refr_avg_time, perf->calculated.render_real_avg_time, perf->calculated.flush_avg_time
);
#endif /*LV_USE_PERF_MONITOR_LOG_MODE*/
}
#endif
#if LV_USE_MEM_MONITOR
static void mem_update_timer_cb(lv_timer_t * t)
{
lv_mem_monitor_t * mem_mon = lv_timer_get_user_data(t);
lv_mem_monitor(mem_mon);
lv_subject_set_pointer(&sysmon_mem.subject, mem_mon);
}
static void mem_observer_cb(lv_subject_t * subject, lv_observer_t * observer)
{
lv_obj_t * label = lv_observer_get_target(observer);
const lv_mem_monitor_t * mon = lv_subject_get_pointer(subject);
uint32_t used_size = mon->total_size - mon->free_size;;
uint32_t used_kb = used_size / 1024;
uint32_t used_kb_tenth = (used_size - (used_kb * 1024)) / 102;
lv_label_set_text_fmt(label,
"%"LV_PRIu32 ".%"LV_PRIu32 " kB, %d%%\n"
"%d%% frag.",
used_kb, used_kb_tenth, mon->used_pct,
mon->frag_pct);
}
#endif
static void sysmon_backend_init_async_cb(void * user_data)
{
LV_UNUSED(user_data);
#if LV_USE_PERF_MONITOR
lv_display_add_event(lv_display_get_default(), perf_monitor_disp_event_cb, LV_EVENT_ALL, NULL);
#if !LV_USE_PERF_MONITOR_LOG_MODE
lv_obj_t * obj1 = lv_sysmon_create(lv_layer_sys());
lv_obj_align(obj1, LV_USE_PERF_MONITOR_POS, 0, 0);
lv_subject_add_observer_obj(&sysmon_perf.subject, perf_observer_cb, obj1, NULL);
#endif
#endif
#if LV_USE_MEM_MONITOR
lv_obj_t * obj2 = lv_sysmon_create(lv_layer_sys());
lv_obj_align(obj2, LV_USE_MEM_MONITOR_POS, 0, 0);
lv_subject_add_observer_obj(&sysmon_mem.subject, mem_observer_cb, obj2, NULL);
#endif
}
#endif /*LV_USE_SYSMON*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes/lv_theme.c | /**
* @file lv_theme.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../lvgl.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void apply_theme(lv_theme_t * th, lv_obj_t * obj);
static void apply_theme_recursion(lv_theme_t * th, lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_theme_t * lv_theme_get_from_obj(lv_obj_t * obj)
{
lv_display_t * disp = obj ? lv_obj_get_disp(obj) : lv_display_get_default();
return lv_display_get_theme(disp);
}
/**
* Apply the active theme on an object
* @param obj pointer to an object
* @param name the name of the theme element to apply. E.g. `LV_THEME_BTN`
*/
void lv_theme_apply(lv_obj_t * obj)
{
lv_theme_t * th = lv_theme_get_from_obj(obj);
if(th == NULL) return;
lv_obj_remove_style_all(obj);
apply_theme_recursion(th, obj); /*Apply the theme including the base theme(s)*/
}
/**
* Set a base theme for a theme.
* The styles from the base them will be added before the styles of the current theme.
* Arbitrary long chain of themes can be created by setting base themes.
* @param new_theme pointer to theme which base should be set
* @param base pointer to the base theme
*/
void lv_theme_set_parent(lv_theme_t * new_theme, lv_theme_t * base)
{
new_theme->parent = base;
}
/**
* Set a callback for a theme.
* The callback is used to add styles to different objects
* @param theme pointer to theme which callback should be set
* @param cb pointer to the callback
*/
void lv_theme_set_apply_cb(lv_theme_t * theme, lv_theme_apply_cb_t apply_cb)
{
theme->apply_cb = apply_cb;
}
const lv_font_t * lv_theme_get_font_small(lv_obj_t * obj)
{
lv_theme_t * th = lv_theme_get_from_obj(obj);
return th ? th->font_small : LV_FONT_DEFAULT;
}
const lv_font_t * lv_theme_get_font_normal(lv_obj_t * obj)
{
lv_theme_t * th = lv_theme_get_from_obj(obj);
return th ? th->font_normal : LV_FONT_DEFAULT;
}
const lv_font_t * lv_theme_get_font_large(lv_obj_t * obj)
{
lv_theme_t * th = lv_theme_get_from_obj(obj);
return th ? th->font_large : LV_FONT_DEFAULT;
}
lv_color_t lv_theme_get_color_primary(lv_obj_t * obj)
{
lv_theme_t * th = lv_theme_get_from_obj(obj);
return th ? th->color_primary : lv_palette_main(LV_PALETTE_BLUE_GREY);
}
lv_color_t lv_theme_get_color_secondary(lv_obj_t * obj)
{
lv_theme_t * th = lv_theme_get_from_obj(obj);
return th ? th->color_secondary : lv_palette_main(LV_PALETTE_BLUE);
}
/**********************
* STATIC FUNCTIONS
**********************/
static void apply_theme(lv_theme_t * th, lv_obj_t * obj)
{
if(th->parent) apply_theme(th->parent, obj);
if(th->apply_cb) th->apply_cb(th, obj);
}
static void apply_theme_recursion(lv_theme_t * th, lv_obj_t * obj)
{
const lv_obj_class_t * original_class_p = obj->class_p;
if(obj->class_p->base_class && obj->class_p->theme_inheritable == LV_OBJ_CLASS_THEME_INHERITABLE_TRUE) {
/*Apply the base class theme in obj*/
obj->class_p = obj->class_p->base_class;
/*apply the base first*/
apply_theme_recursion(th, obj);
}
/*Restore the original class*/
obj->class_p = original_class_p;
apply_theme(th, obj);
}
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes/lv_theme.h | /**
*@file lv_theme.h
*
*/
#ifndef LV_THEME_H
#define LV_THEME_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../core/lv_obj.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
struct _lv_theme_t;
struct _lv_display_t;
typedef void (*lv_theme_apply_cb_t)(struct _lv_theme_t *, lv_obj_t *);
typedef struct _lv_theme_t {
lv_theme_apply_cb_t apply_cb;
struct _lv_theme_t * parent; /**< Apply the current theme's style on top of this theme.*/
void * user_data;
struct _lv_display_t * disp;
lv_color_t color_primary;
lv_color_t color_secondary;
const lv_font_t * font_small;
const lv_font_t * font_normal;
const lv_font_t * font_large;
uint32_t flags; /*Any custom flag used by the theme*/
} lv_theme_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Get the theme assigned to the display of the object
* @param obj pointer to a theme object
* @return the theme of the object's display (can be NULL)
*/
lv_theme_t * lv_theme_get_from_obj(lv_obj_t * obj);
/**
* Apply the active theme on an object
* @param obj pointer to an object
*/
void lv_theme_apply(lv_obj_t * obj);
/**
* Set a base theme for a theme.
* The styles from the base them will be added before the styles of the current theme.
* Arbitrary long chain of themes can be created by setting base themes.
* @param new_theme pointer to theme which base should be set
* @param parent pointer to the base theme
*/
void lv_theme_set_parent(lv_theme_t * new_theme, lv_theme_t * parent);
/**
* Set an apply callback for a theme.
* The apply callback is used to add styles to different objects
* @param theme pointer to theme which callback should be set
* @param apply_cb pointer to the callback
*/
void lv_theme_set_apply_cb(lv_theme_t * theme, lv_theme_apply_cb_t apply_cb);
/**
* Get the small font of the theme
* @param obj pointer to an object
* @return pointer to the font
*/
const lv_font_t * lv_theme_get_font_small(lv_obj_t * obj);
/**
* Get the normal font of the theme
* @param obj pointer to an object
* @return pointer to the font
*/
const lv_font_t * lv_theme_get_font_normal(lv_obj_t * obj);
/**
* Get the subtitle font of the theme
* @param obj pointer to an object
* @return pointer to the font
*/
const lv_font_t * lv_theme_get_font_large(lv_obj_t * obj);
/**
* Get the primary color of the theme
* @param obj pointer to an object
* @return the color
*/
lv_color_t lv_theme_get_color_primary(lv_obj_t * obj);
/**
* Get the secondary color of the theme
* @param obj pointer to an object
* @return the color
*/
lv_color_t lv_theme_get_color_secondary(lv_obj_t * obj);
/**********************
* MACROS
**********************/
#include "default/lv_theme_default.h"
#include "mono/lv_theme_mono.h"
#include "basic/lv_theme_basic.h"
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_THEME_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes/basic/lv_theme_basic.c | /**
* @file lv_theme_basic.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h" /*To see all the widgets*/
#if LV_USE_THEME_BASIC
#include "lv_theme_basic.h"
#include "../../core/lv_global.h"
/*********************
* DEFINES
*********************/
#define theme_def (LV_GLOBAL_DEFAULT()->theme_basic)
#define COLOR_SCR lv_palette_lighten(LV_PALETTE_GREY, 4)
#define COLOR_WHITE lv_color_white()
#define COLOR_LIGHT lv_palette_lighten(LV_PALETTE_GREY, 2)
#define COLOR_DARK lv_palette_main(LV_PALETTE_GREY)
#define COLOR_DIM lv_palette_darken(LV_PALETTE_GREY, 2)
#define SCROLLBAR_WIDTH 2
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_style_t scr;
lv_style_t transp;
lv_style_t white;
lv_style_t light;
lv_style_t dark;
lv_style_t dim;
lv_style_t scrollbar;
#if LV_USE_ARC
lv_style_t arc_line;
lv_style_t arc_knob;
#endif
#if LV_USE_TEXTAREA
lv_style_t ta_cursor;
#endif
} my_theme_styles_t;
typedef struct _my_theme_t {
lv_theme_t base;
my_theme_styles_t styles;
bool inited;
} my_theme_t;
/**********************
* STATIC PROTOTYPES
**********************/
static void style_init_reset(lv_style_t * style);
static void theme_apply(lv_theme_t * th, lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* STATIC FUNCTIONS
**********************/
static void style_init(struct _my_theme_t * theme)
{
style_init_reset(&theme->styles.scrollbar);
lv_style_set_bg_opa(&theme->styles.scrollbar, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.scrollbar, COLOR_DARK);
lv_style_set_width(&theme->styles.scrollbar, SCROLLBAR_WIDTH);
style_init_reset(&theme->styles.scr);
lv_style_set_bg_opa(&theme->styles.scr, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.scr, COLOR_SCR);
lv_style_set_text_color(&theme->styles.scr, COLOR_DIM);
style_init_reset(&theme->styles.transp);
lv_style_set_bg_opa(&theme->styles.transp, LV_OPA_TRANSP);
style_init_reset(&theme->styles.white);
lv_style_set_bg_opa(&theme->styles.white, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.white, COLOR_WHITE);
lv_style_set_line_width(&theme->styles.white, 1);
lv_style_set_line_color(&theme->styles.white, COLOR_WHITE);
lv_style_set_arc_width(&theme->styles.white, 2);
lv_style_set_arc_color(&theme->styles.white, COLOR_WHITE);
style_init_reset(&theme->styles.light);
lv_style_set_bg_opa(&theme->styles.light, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.light, COLOR_LIGHT);
lv_style_set_line_width(&theme->styles.light, 1);
lv_style_set_line_color(&theme->styles.light, COLOR_LIGHT);
lv_style_set_arc_width(&theme->styles.light, 2);
lv_style_set_arc_color(&theme->styles.light, COLOR_LIGHT);
style_init_reset(&theme->styles.dark);
lv_style_set_bg_opa(&theme->styles.dark, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.dark, COLOR_DARK);
lv_style_set_line_width(&theme->styles.dark, 1);
lv_style_set_line_color(&theme->styles.dark, COLOR_DARK);
lv_style_set_arc_width(&theme->styles.dark, 2);
lv_style_set_arc_color(&theme->styles.dark, COLOR_DARK);
style_init_reset(&theme->styles.dim);
lv_style_set_bg_opa(&theme->styles.dim, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.dim, COLOR_DIM);
lv_style_set_line_width(&theme->styles.dim, 1);
lv_style_set_line_color(&theme->styles.dim, COLOR_DIM);
lv_style_set_arc_width(&theme->styles.dim, 2);
lv_style_set_arc_color(&theme->styles.dim, COLOR_DIM);
#if LV_USE_ARC
style_init_reset(&theme->styles.arc_line);
lv_style_set_arc_width(&theme->styles.arc_line, 6);
style_init_reset(&theme->styles.arc_knob);
lv_style_set_pad_all(&theme->styles.arc_knob, 5);
#endif
#if LV_USE_TEXTAREA
style_init_reset(&theme->styles.ta_cursor);
lv_style_set_border_side(&theme->styles.ta_cursor, LV_BORDER_SIDE_LEFT);
lv_style_set_border_color(&theme->styles.ta_cursor, COLOR_DIM);
lv_style_set_border_width(&theme->styles.ta_cursor, 2);
lv_style_set_bg_opa(&theme->styles.ta_cursor, LV_OPA_TRANSP);
lv_style_set_anim_time(&theme->styles.ta_cursor, 500);
#endif
}
/**********************
* GLOBAL FUNCTIONS
**********************/
bool lv_theme_basic_is_inited(void)
{
struct _my_theme_t * theme = theme_def;
if(theme == NULL) return false;
return theme->inited;
}
void lv_theme_basic_deinit(void)
{
if(theme_def) {
lv_free(theme_def);
theme_def = NULL;
}
}
lv_theme_t * lv_theme_basic_init(lv_display_t * disp)
{
/*This trick is required only to avoid the garbage collection of
*styles' data if LVGL is used in a binding (e.g. Micropython)
*In a general case styles could be in simple `static lv_style_t my_style...` variables*/
if(!lv_theme_basic_is_inited()) {
theme_def = (my_theme_t *)lv_malloc(sizeof(my_theme_t));
lv_memzero(theme_def, sizeof(my_theme_t));
}
struct _my_theme_t * theme = theme_def;
theme->base.disp = disp;
theme->base.font_small = LV_FONT_DEFAULT;
theme->base.font_normal = LV_FONT_DEFAULT;
theme->base.font_large = LV_FONT_DEFAULT;
theme->base.apply_cb = theme_apply;
style_init(theme);
if(disp == NULL || lv_display_get_theme(disp) == (lv_theme_t *)theme) {
lv_obj_report_style_change(NULL);
}
theme->inited = true;
return (lv_theme_t *)theme_def;
}
static void theme_apply(lv_theme_t * th, lv_obj_t * obj)
{
LV_UNUSED(th);
struct _my_theme_t * theme = theme_def;
if(lv_obj_get_parent(obj) == NULL) {
lv_obj_add_style(obj, &theme->styles.scr, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
return;
}
if(lv_obj_check_type(obj, &lv_obj_class)) {
#if LV_USE_TABVIEW
lv_obj_t * parent = lv_obj_get_parent(obj);
/*Tabview content area*/
if(lv_obj_check_type(parent, &lv_tabview_class)) {
lv_obj_add_style(obj, &theme->styles.scr, 0);
return;
}
/*Tabview pages*/
else if(lv_obj_check_type(lv_obj_get_parent(parent), &lv_tabview_class)) {
lv_obj_add_style(obj, &theme->styles.scr, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
return;
}
#endif
#if LV_USE_WIN
/*Header*/
if(lv_obj_get_index(obj) == 0 && lv_obj_check_type(lv_obj_get_parent(obj), &lv_win_class)) {
lv_obj_add_style(obj, &theme->styles.light, 0);
return;
}
/*Content*/
else if(lv_obj_get_index(obj) == 1 && lv_obj_check_type(lv_obj_get_parent(obj), &lv_win_class)) {
lv_obj_add_style(obj, &theme->styles.light, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
return;
}
#endif
lv_obj_add_style(obj, &theme->styles.white, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
}
#if LV_USE_BTN
else if(lv_obj_check_type(obj, &lv_button_class)) {
lv_obj_add_style(obj, &theme->styles.dark, 0);
}
#endif
#if LV_USE_BTNMATRIX
else if(lv_obj_check_type(obj, &lv_buttonmatrix_class)) {
#if LV_USE_MSGBOX
if(lv_obj_check_type(lv_obj_get_parent(obj), &lv_msgbox_class)) {
lv_obj_add_style(obj, &theme->styles.light, LV_PART_ITEMS);
return;
}
#endif
#if LV_USE_TABVIEW
if(lv_obj_check_type(lv_obj_get_parent(obj), &lv_tabview_class)) {
lv_obj_add_style(obj, &theme->styles.light, LV_PART_ITEMS);
return;
}
#endif
lv_obj_add_style(obj, &theme->styles.white, 0);
lv_obj_add_style(obj, &theme->styles.light, LV_PART_ITEMS);
}
#endif
#if LV_USE_BAR
else if(lv_obj_check_type(obj, &lv_bar_class)) {
lv_obj_add_style(obj, &theme->styles.light, 0);
lv_obj_add_style(obj, &theme->styles.dark, LV_PART_INDICATOR);
}
#endif
#if LV_USE_SLIDER
else if(lv_obj_check_type(obj, &lv_slider_class)) {
lv_obj_add_style(obj, &theme->styles.light, 0);
lv_obj_add_style(obj, &theme->styles.dark, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.dim, LV_PART_KNOB);
}
#endif
#if LV_USE_TABLE
else if(lv_obj_check_type(obj, &lv_table_class)) {
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.light, LV_PART_ITEMS);
}
#endif
#if LV_USE_CHECKBOX
else if(lv_obj_check_type(obj, &lv_checkbox_class)) {
lv_obj_add_style(obj, &theme->styles.light, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.dark, LV_PART_INDICATOR | LV_STATE_CHECKED);
}
#endif
#if LV_USE_SWITCH
else if(lv_obj_check_type(obj, &lv_switch_class)) {
lv_obj_add_style(obj, &theme->styles.light, 0);
lv_obj_add_style(obj, &theme->styles.dim, LV_PART_KNOB);
}
#endif
#if LV_USE_CHART
else if(lv_obj_check_type(obj, &lv_chart_class)) {
lv_obj_add_style(obj, &theme->styles.white, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.light, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.dark, LV_PART_CURSOR);
}
#endif
#if LV_USE_ROLLER
else if(lv_obj_check_type(obj, &lv_roller_class)) {
lv_obj_add_style(obj, &theme->styles.light, 0);
lv_obj_add_style(obj, &theme->styles.dark, LV_PART_SELECTED);
}
#endif
#if LV_USE_DROPDOWN
else if(lv_obj_check_type(obj, &lv_dropdown_class)) {
lv_obj_add_style(obj, &theme->styles.white, 0);
}
else if(lv_obj_check_type(obj, &lv_dropdownlist_class)) {
lv_obj_add_style(obj, &theme->styles.white, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.light, LV_PART_SELECTED);
lv_obj_add_style(obj, &theme->styles.dark, LV_PART_SELECTED | LV_STATE_CHECKED);
}
#endif
#if LV_USE_ARC
else if(lv_obj_check_type(obj, &lv_arc_class)) {
lv_obj_add_style(obj, &theme->styles.light, 0);
lv_obj_add_style(obj, &theme->styles.transp, 0);
lv_obj_add_style(obj, &theme->styles.arc_line, 0);
lv_obj_add_style(obj, &theme->styles.dark, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.arc_line, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.dim, LV_PART_KNOB);
lv_obj_add_style(obj, &theme->styles.arc_knob, LV_PART_KNOB);
}
#endif
#if LV_USE_SPINNER
else if(lv_obj_check_type(obj, &lv_spinner_class)) {
lv_obj_add_style(obj, &theme->styles.light, 0);
lv_obj_add_style(obj, &theme->styles.transp, 0);
lv_obj_add_style(obj, &theme->styles.arc_line, 0);
lv_obj_add_style(obj, &theme->styles.dark, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.arc_line, LV_PART_INDICATOR);
}
#endif
//#if LV_USE_METER
// else if(lv_obj_check_type(obj, &lv_meter_class)) {
// lv_obj_add_style(obj, &theme->styles.light, 0);
// }
//#endif
#if LV_USE_TEXTAREA
else if(lv_obj_check_type(obj, &lv_textarea_class)) {
lv_obj_add_style(obj, &theme->styles.white, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.ta_cursor, LV_PART_CURSOR | LV_STATE_FOCUSED);
}
#endif
#if LV_USE_CALENDAR
else if(lv_obj_check_type(obj, &lv_calendar_class)) {
lv_obj_add_style(obj, &theme->styles.light, 0);
}
#endif
#if LV_USE_KEYBOARD
else if(lv_obj_check_type(obj, &lv_keyboard_class)) {
lv_obj_add_style(obj, &theme->styles.scr, 0);
lv_obj_add_style(obj, &theme->styles.white, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.light, LV_PART_ITEMS | LV_STATE_CHECKED);
}
#endif
#if LV_USE_LIST
else if(lv_obj_check_type(obj, &lv_list_class)) {
lv_obj_add_style(obj, &theme->styles.light, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
return;
}
else if(lv_obj_check_type(obj, &lv_list_text_class)) {
}
else if(lv_obj_check_type(obj, &lv_list_button_class)) {
lv_obj_add_style(obj, &theme->styles.dark, 0);
}
#endif
#if LV_USE_MSGBOX
else if(lv_obj_check_type(obj, &lv_msgbox_class)) {
lv_obj_add_style(obj, &theme->styles.light, 0);
return;
}
#endif
#if LV_USE_SPINBOX
else if(lv_obj_check_type(obj, &lv_spinbox_class)) {
lv_obj_add_style(obj, &theme->styles.light, 0);
lv_obj_add_style(obj, &theme->styles.dark, LV_PART_CURSOR);
}
#endif
#if LV_USE_TILEVIEW
else if(lv_obj_check_type(obj, &lv_tileview_class)) {
lv_obj_add_style(obj, &theme->styles.scr, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
}
else if(lv_obj_check_type(obj, &lv_tileview_tile_class)) {
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
}
#endif
#if LV_USE_LED
else if(lv_obj_check_type(obj, &lv_led_class)) {
lv_obj_add_style(obj, &theme->styles.light, 0);
}
#endif
}
/**********************
* STATIC FUNCTIONS
**********************/
static void style_init_reset(lv_style_t * style)
{
if(lv_theme_basic_is_inited()) {
lv_style_reset(style);
}
else {
lv_style_init(style);
}
}
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes/basic/lv_theme_basic.h | /**
* @file lv_theme_basic.h
*
*/
#ifndef LV_THEME_BASIC_H
#define LV_THEME_BASIC_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_theme.h"
#include "../../display/lv_display.h"
#if LV_USE_THEME_BASIC
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Initialize the theme
* @param disp pointer to display to attach the theme
* @return a pointer to reference this theme later
*/
lv_theme_t * lv_theme_basic_init(lv_display_t * disp);
/**
* Check if the theme is initialized
* @return true if default theme is initialized, false otherwise
*/
bool lv_theme_basic_is_inited(void);
/**
* Deinitialize the basic theme
*/
void lv_theme_basic_deinit(void);
/**********************
* MACROS
**********************/
#endif
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_THEME_BASIC_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes/mono/lv_theme_mono.h | /**
* @file lv_theme_mono.h
*
*/
#ifndef LV_USE_THEME_MONO_H
#define LV_USE_THEME_MONO_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_theme.h"
#if LV_USE_THEME_MONO
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Initialize the theme
* @param disp pointer to display
* @param dark_bg
* @param font pointer to a font to use.
* @return a pointer to reference this theme later
*/
lv_theme_t * lv_theme_mono_init(lv_display_t * disp, bool dark_bg, const lv_font_t * font);
/**
* Check if the theme is initialized
* @return true if default theme is initialized, false otherwise
*/
bool lv_theme_mono_is_inited(void);
/**
* Deinitialize the mono theme
*/
void lv_theme_mono_deinit(void);
/**********************
* MACROS
**********************/
#endif
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_USE_THEME_MONO_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes/mono/lv_theme_mono.c | /**
* @file lv_theme_mono.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_THEME_MONO
#include "lv_theme_mono.h"
#include "../../core/lv_global.h"
/*********************
* DEFINES
*********************/
#define theme_def (LV_GLOBAL_DEFAULT()->theme_mono)
#define COLOR_FG dark_bg ? lv_color_white() : lv_color_black()
#define COLOR_BG dark_bg ? lv_color_black() : lv_color_white()
#define BORDER_W_NORMAL 1
#define BORDER_W_PR 3
#define BORDER_W_DIS 0
#define BORDER_W_FOCUS 1
#define BORDER_W_EDIT 2
#define PAD_DEF 4
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_style_t scr;
lv_style_t card;
lv_style_t scrollbar;
lv_style_t btn;
lv_style_t pr;
lv_style_t inv;
lv_style_t disabled;
lv_style_t focus;
lv_style_t edit;
lv_style_t pad_gap;
lv_style_t pad_zero;
lv_style_t no_radius;
lv_style_t radius_circle;
lv_style_t large_border;
lv_style_t large_line_space;
lv_style_t underline;
#if LV_USE_TEXTAREA
lv_style_t ta_cursor;
#endif
#if LV_USE_CHART
lv_style_t chart_indic;
#endif
} my_theme_styles_t;
typedef struct _my_theme_t {
lv_theme_t base;
my_theme_styles_t styles;
bool inited;
} my_theme_t;
/**********************
* STATIC PROTOTYPES
**********************/
static void style_init_reset(lv_style_t * style);
static void theme_apply(lv_theme_t * th, lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* STATIC FUNCTIONS
**********************/
static void style_init(struct _my_theme_t * theme, bool dark_bg, const lv_font_t * font)
{
style_init_reset(&theme->styles.scrollbar);
lv_style_set_bg_opa(&theme->styles.scrollbar, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.scrollbar, COLOR_FG);
lv_style_set_width(&theme->styles.scrollbar, PAD_DEF);
style_init_reset(&theme->styles.scr);
lv_style_set_bg_opa(&theme->styles.scr, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.scr, COLOR_BG);
lv_style_set_text_color(&theme->styles.scr, COLOR_FG);
lv_style_set_pad_row(&theme->styles.scr, PAD_DEF);
lv_style_set_pad_column(&theme->styles.scr, PAD_DEF);
lv_style_set_text_font(&theme->styles.scr, font);
style_init_reset(&theme->styles.card);
lv_style_set_bg_opa(&theme->styles.card, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.card, COLOR_BG);
lv_style_set_border_color(&theme->styles.card, COLOR_FG);
lv_style_set_radius(&theme->styles.card, 2);
lv_style_set_border_width(&theme->styles.card, BORDER_W_NORMAL);
lv_style_set_pad_all(&theme->styles.card, PAD_DEF);
lv_style_set_pad_gap(&theme->styles.card, PAD_DEF);
lv_style_set_text_color(&theme->styles.card, COLOR_FG);
lv_style_set_line_width(&theme->styles.card, 2);
lv_style_set_line_color(&theme->styles.card, COLOR_FG);
lv_style_set_arc_width(&theme->styles.card, 2);
lv_style_set_arc_color(&theme->styles.card, COLOR_FG);
lv_style_set_outline_color(&theme->styles.card, COLOR_FG);
lv_style_set_anim_time(&theme->styles.card, 300);
style_init_reset(&theme->styles.pr);
lv_style_set_border_width(&theme->styles.pr, BORDER_W_PR);
style_init_reset(&theme->styles.inv);
lv_style_set_bg_opa(&theme->styles.inv, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.inv, COLOR_FG);
lv_style_set_border_color(&theme->styles.inv, COLOR_BG);
lv_style_set_line_color(&theme->styles.inv, COLOR_BG);
lv_style_set_arc_color(&theme->styles.inv, COLOR_BG);
lv_style_set_text_color(&theme->styles.inv, COLOR_BG);
lv_style_set_outline_color(&theme->styles.inv, COLOR_BG);
style_init_reset(&theme->styles.disabled);
lv_style_set_border_width(&theme->styles.disabled, BORDER_W_DIS);
style_init_reset(&theme->styles.focus);
lv_style_set_outline_width(&theme->styles.focus, 1);
lv_style_set_outline_pad(&theme->styles.focus, BORDER_W_FOCUS);
style_init_reset(&theme->styles.edit);
lv_style_set_outline_width(&theme->styles.edit, BORDER_W_EDIT);
style_init_reset(&theme->styles.large_border);
lv_style_set_border_width(&theme->styles.large_border, BORDER_W_EDIT);
style_init_reset(&theme->styles.pad_gap);
lv_style_set_pad_gap(&theme->styles.pad_gap, PAD_DEF);
style_init_reset(&theme->styles.pad_zero);
lv_style_set_pad_all(&theme->styles.pad_zero, 0);
lv_style_set_pad_gap(&theme->styles.pad_zero, 0);
style_init_reset(&theme->styles.no_radius);
lv_style_set_radius(&theme->styles.no_radius, 0);
style_init_reset(&theme->styles.radius_circle);
lv_style_set_radius(&theme->styles.radius_circle, LV_RADIUS_CIRCLE);
style_init_reset(&theme->styles.large_line_space);
lv_style_set_text_line_space(&theme->styles.large_line_space, 6);
style_init_reset(&theme->styles.underline);
lv_style_set_text_decor(&theme->styles.underline, LV_TEXT_DECOR_UNDERLINE);
#if LV_USE_TEXTAREA
style_init_reset(&theme->styles.ta_cursor);
lv_style_set_border_side(&theme->styles.ta_cursor, LV_BORDER_SIDE_LEFT);
lv_style_set_border_color(&theme->styles.ta_cursor, COLOR_FG);
lv_style_set_border_width(&theme->styles.ta_cursor, 2);
lv_style_set_bg_opa(&theme->styles.ta_cursor, LV_OPA_TRANSP);
lv_style_set_anim_time(&theme->styles.ta_cursor, 500);
#endif
#if LV_USE_CHART
style_init_reset(&theme->styles.chart_indic);
lv_style_set_radius(&theme->styles.chart_indic, LV_RADIUS_CIRCLE);
lv_style_set_size(&theme->styles.chart_indic, lv_display_dpx(theme->base.disp, 8), lv_display_dpx(theme->base.disp, 8));
lv_style_set_bg_color(&theme->styles.chart_indic, COLOR_FG);
lv_style_set_bg_opa(&theme->styles.chart_indic, LV_OPA_COVER);
#endif
}
/**********************
* GLOBAL FUNCTIONS
**********************/
bool lv_theme_mono_is_inited(void)
{
struct _my_theme_t * theme = theme_def;
if(theme == NULL) return false;
return theme->inited;
}
void lv_theme_mono_deinit(void)
{
if(theme_def) {
lv_free(theme_def);
theme_def = NULL;
}
}
lv_theme_t * lv_theme_mono_init(lv_display_t * disp, bool dark_bg, const lv_font_t * font)
{
/*This trick is required only to avoid the garbage collection of
*styles' data if LVGL is used in a binding (e.g. Micropython)
*In a general case styles could be in simple `static lv_style_t my_style...` variables*/
if(!lv_theme_mono_is_inited()) {
theme_def = (my_theme_t *)lv_malloc(sizeof(my_theme_t));
lv_memzero(theme_def, sizeof(my_theme_t));
}
struct _my_theme_t * theme = theme_def;
theme->base.disp = disp;
theme->base.font_small = LV_FONT_DEFAULT;
theme->base.font_normal = LV_FONT_DEFAULT;
theme->base.font_large = LV_FONT_DEFAULT;
theme->base.apply_cb = theme_apply;
style_init(theme, dark_bg, font);
if(disp == NULL || lv_display_get_theme(disp) == (lv_theme_t *) theme) lv_obj_report_style_change(NULL);
theme->inited = true;
return (lv_theme_t *)theme_def;
}
static void theme_apply(lv_theme_t * th, lv_obj_t * obj)
{
LV_UNUSED(th);
struct _my_theme_t * theme = theme_def;
if(lv_obj_get_parent(obj) == NULL) {
lv_obj_add_style(obj, &theme->styles.scr, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
return;
}
if(lv_obj_check_type(obj, &lv_obj_class)) {
#if LV_USE_TABVIEW
lv_obj_t * parent = lv_obj_get_parent(obj);
/*Tabview content area*/
if(lv_obj_check_type(parent, &lv_tabview_class)) {
return;
}
/*Tabview pages*/
else if(lv_obj_check_type(lv_obj_get_parent(parent), &lv_tabview_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.no_radius, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
return;
}
#endif
#if LV_USE_WIN
/*Header*/
if(lv_obj_get_index(obj) == 0 && lv_obj_check_type(lv_obj_get_parent(obj), &lv_win_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.no_radius, 0);
return;
}
/*Content*/
else if(lv_obj_get_index(obj) == 1 && lv_obj_check_type(lv_obj_get_parent(obj), &lv_win_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.no_radius, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
return;
}
#endif
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
}
#if LV_USE_BTN
else if(lv_obj_check_type(obj, &lv_button_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.pr, LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.inv, LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.disabled, LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.edit, LV_STATE_EDITED);
}
#endif
#if LV_USE_BTNMATRIX
else if(lv_obj_check_type(obj, &lv_buttonmatrix_class)) {
#if LV_USE_MSGBOX
if(lv_obj_check_type(lv_obj_get_parent(obj), &lv_msgbox_class)) {
lv_obj_add_style(obj, &theme->styles.pad_gap, 0);
lv_obj_add_style(obj, &theme->styles.card, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.pr, LV_PART_ITEMS | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.disabled, LV_PART_ITEMS | LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.underline, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.large_border, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
return;
}
#endif
#if LV_USE_TABVIEW
if(lv_obj_check_type(lv_obj_get_parent(obj), &lv_tabview_class)) {
lv_obj_add_style(obj, &theme->styles.pad_gap, 0);
lv_obj_add_style(obj, &theme->styles.card, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.pr, LV_PART_ITEMS | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.inv, LV_PART_ITEMS | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.disabled, LV_PART_ITEMS | LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.underline, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.large_border, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
return;
}
#endif
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.card, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.pr, LV_PART_ITEMS | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.inv, LV_PART_ITEMS | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.disabled, LV_PART_ITEMS | LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.underline, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.large_border, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
}
#endif
#if LV_USE_BAR
else if(lv_obj_check_type(obj, &lv_bar_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.pad_zero, 0);
lv_obj_add_style(obj, &theme->styles.inv, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
}
#endif
#if LV_USE_SLIDER
else if(lv_obj_check_type(obj, &lv_slider_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.pad_zero, 0);
lv_obj_add_style(obj, &theme->styles.inv, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.card, LV_PART_KNOB);
lv_obj_add_style(obj, &theme->styles.radius_circle, LV_PART_KNOB);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.edit, LV_STATE_EDITED);
}
#endif
#if LV_USE_TABLE
else if(lv_obj_check_type(obj, &lv_table_class)) {
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.card, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.no_radius, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.pr, LV_PART_ITEMS | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.inv, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.edit, LV_STATE_EDITED);
}
#endif
#if LV_USE_CHECKBOX
else if(lv_obj_check_type(obj, &lv_checkbox_class)) {
lv_obj_add_style(obj, &theme->styles.pad_gap, LV_PART_MAIN);
lv_obj_add_style(obj, &theme->styles.card, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.disabled, LV_PART_INDICATOR | LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.inv, LV_PART_INDICATOR | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.pr, LV_PART_INDICATOR | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.edit, LV_STATE_EDITED);
}
#endif
#if LV_USE_SWITCH
else if(lv_obj_check_type(obj, &lv_switch_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.radius_circle, 0);
lv_obj_add_style(obj, &theme->styles.pad_zero, 0);
lv_obj_add_style(obj, &theme->styles.inv, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.radius_circle, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.card, LV_PART_KNOB);
lv_obj_add_style(obj, &theme->styles.radius_circle, LV_PART_KNOB);
lv_obj_add_style(obj, &theme->styles.pad_zero, LV_PART_KNOB);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.edit, LV_STATE_EDITED);
}
#endif
#if LV_USE_CHART
else if(lv_obj_check_type(obj, &lv_chart_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.chart_indic, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.card, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.card, LV_PART_CURSOR);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
}
#endif
#if LV_USE_ROLLER
else if(lv_obj_check_type(obj, &lv_roller_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.large_line_space, 0);
lv_obj_add_style(obj, &theme->styles.inv, LV_PART_SELECTED);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.edit, LV_STATE_EDITED);
}
#endif
#if LV_USE_DROPDOWN
else if(lv_obj_check_type(obj, &lv_dropdown_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.pr, LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.edit, LV_STATE_EDITED);
}
else if(lv_obj_check_type(obj, &lv_dropdownlist_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.large_line_space, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.inv, LV_PART_SELECTED | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.pr, LV_PART_SELECTED | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.edit, LV_STATE_EDITED);
}
#endif
#if LV_USE_ARC
else if(lv_obj_check_type(obj, &lv_arc_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.inv, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.pad_zero, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.card, LV_PART_KNOB);
lv_obj_add_style(obj, &theme->styles.radius_circle, LV_PART_KNOB);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.edit, LV_STATE_EDITED);
}
#endif
//#if LV_USE_METER
// else if(lv_obj_check_type(obj, &lv_meter_class)) {
// lv_obj_add_style(obj, &theme->styles.card, 0);
// }
//#endif
#if LV_USE_TEXTAREA
else if(lv_obj_check_type(obj, &lv_textarea_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.ta_cursor, LV_PART_CURSOR | LV_STATE_FOCUSED);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUSED);
lv_obj_add_style(obj, &theme->styles.edit, LV_STATE_EDITED);
}
#endif
#if LV_USE_CALENDAR
else if(lv_obj_check_type(obj, &lv_calendar_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.no_radius, 0);
lv_obj_add_style(obj, &theme->styles.pr, LV_PART_ITEMS | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.disabled, LV_PART_ITEMS | LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.edit, LV_STATE_EDITED);
lv_obj_add_style(obj, &theme->styles.large_border, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
}
#endif
#if LV_USE_KEYBOARD
else if(lv_obj_check_type(obj, &lv_keyboard_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.card, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.pr, LV_PART_ITEMS | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.inv, LV_PART_ITEMS | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.edit, LV_STATE_EDITED);
lv_obj_add_style(obj, &theme->styles.large_border, LV_PART_ITEMS | LV_STATE_EDITED);
}
#endif
#if LV_USE_LIST
else if(lv_obj_check_type(obj, &lv_list_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
return;
}
else if(lv_obj_check_type(obj, &lv_list_text_class)) {
}
else if(lv_obj_check_type(obj, &lv_list_button_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.pr, LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.large_border, LV_STATE_EDITED);
}
#endif
#if LV_USE_MSGBOX
else if(lv_obj_check_type(obj, &lv_msgbox_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
return;
}
#endif
#if LV_USE_SPINBOX
else if(lv_obj_check_type(obj, &lv_spinbox_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.inv, LV_PART_CURSOR);
lv_obj_add_style(obj, &theme->styles.focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.edit, LV_STATE_EDITED);
}
#endif
#if LV_USE_TILEVIEW
else if(lv_obj_check_type(obj, &lv_tileview_class)) {
lv_obj_add_style(obj, &theme->styles.scr, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
}
else if(lv_obj_check_type(obj, &lv_tileview_tile_class)) {
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
}
#endif
#if LV_USE_LED
else if(lv_obj_check_type(obj, &lv_led_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
}
#endif
}
/**********************
* STATIC FUNCTIONS
**********************/
static void style_init_reset(lv_style_t * style)
{
if(lv_theme_mono_is_inited()) {
lv_style_reset(style);
}
else {
lv_style_init(style);
}
}
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes/default/lv_theme_default.h | /**
* @file lv_theme_default.h
*
*/
#ifndef LV_THEME_DEFAULT_H
#define LV_THEME_DEFAULT_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_theme.h"
#if LV_USE_THEME_DEFAULT
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Initialize the theme
* @param disp pointer to display
* @param color_primary the primary color of the theme
* @param color_secondary the secondary color for the theme
* @param dark
* @param font pointer to a font to use.
* @return a pointer to reference this theme later
*/
lv_theme_t * lv_theme_default_init(lv_display_t * disp, lv_color_t color_primary, lv_color_t color_secondary, bool dark,
const lv_font_t * font);
/**
* Get default theme
* @return a pointer to default theme, or NULL if this is not initialized
*/
lv_theme_t * lv_theme_default_get(void);
/**
* Check if default theme is initialized
* @return true if default theme is initialized, false otherwise
*/
bool lv_theme_default_is_inited(void);
/**
* Deinitialize the default theme
*/
void lv_theme_default_deinit(void);
/**********************
* MACROS
**********************/
#endif
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_THEME_DEFAULT_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes | repos/zig_workbench/BaseLVGL/lib/lvgl/src/themes/default/lv_theme_default.c | /**
* @file lv_theme_default.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h" /*To see all the widgets*/
#if LV_USE_THEME_DEFAULT
#include "../lv_theme.h"
#include "../../misc/lv_color.h"
#include "../../core/lv_global.h"
/*********************
* DEFINES
*********************/
#define theme_def (LV_GLOBAL_DEFAULT()->theme_default)
#define MODE_DARK 1
#define RADIUS_DEFAULT _LV_DPX_CALC(theme->disp_dpi, theme->disp_size == DISP_LARGE ? 12 : 8)
/*SCREEN*/
#define LIGHT_COLOR_SCR lv_palette_lighten(LV_PALETTE_GREY, 4)
#define LIGHT_COLOR_CARD lv_color_white()
#define LIGHT_COLOR_TEXT lv_palette_darken(LV_PALETTE_GREY, 4)
#define LIGHT_COLOR_GREY lv_palette_lighten(LV_PALETTE_GREY, 2)
#define DARK_COLOR_SCR lv_color_hex(0x15171A)
#define DARK_COLOR_CARD lv_color_hex(0x282b30)
#define DARK_COLOR_TEXT lv_palette_lighten(LV_PALETTE_GREY, 5)
#define DARK_COLOR_GREY lv_color_hex(0x2f3237)
#define TRANSITION_TIME LV_THEME_DEFAULT_TRANSITION_TIME
#define BORDER_WIDTH _LV_DPX_CALC(theme->disp_dpi, 2)
#define OUTLINE_WIDTH _LV_DPX_CALC(theme->disp_dpi, 3)
#define PAD_DEF _LV_DPX_CALC(theme->disp_dpi, theme->disp_size == DISP_LARGE ? 24 : theme->disp_size == DISP_MEDIUM ? 20 : 16)
#define PAD_SMALL _LV_DPX_CALC(theme->disp_dpi, theme->disp_size == DISP_LARGE ? 14 : theme->disp_size == DISP_MEDIUM ? 12 : 10)
#define PAD_TINY _LV_DPX_CALC(theme->disp_dpi, theme->disp_size == DISP_LARGE ? 8 : theme->disp_size == DISP_MEDIUM ? 6 : 2)
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_style_t scr;
lv_style_t scrollbar;
lv_style_t scrollbar_scrolled;
lv_style_t card;
lv_style_t btn;
/*Utility*/
lv_style_t bg_color_primary;
lv_style_t bg_color_primary_muted;
lv_style_t bg_color_secondary;
lv_style_t bg_color_secondary_muted;
lv_style_t bg_color_grey;
lv_style_t bg_color_white;
lv_style_t pressed;
lv_style_t disabled;
lv_style_t pad_zero;
lv_style_t pad_tiny;
lv_style_t pad_small;
lv_style_t pad_normal;
lv_style_t pad_gap;
lv_style_t line_space_large;
lv_style_t text_align_center;
lv_style_t outline_primary;
lv_style_t outline_secondary;
lv_style_t circle;
lv_style_t no_radius;
lv_style_t clip_corner;
#if LV_THEME_DEFAULT_GROW
lv_style_t grow;
#endif
lv_style_t transition_delayed;
lv_style_t transition_normal;
lv_style_t anim;
lv_style_t anim_fast;
/*Parts*/
lv_style_t knob;
lv_style_t indic;
#if LV_USE_ARC
lv_style_t arc_indic;
lv_style_t arc_indic_primary;
#endif
#if LV_USE_CHART
lv_style_t chart_series, chart_indic, chart_bg;
#endif
#if LV_USE_DROPDOWN
lv_style_t dropdown_list;
#endif
#if LV_USE_CHECKBOX
lv_style_t cb_marker, cb_marker_checked;
#endif
#if LV_USE_SWITCH
lv_style_t switch_knob;
#endif
#if LV_USE_LINE
lv_style_t line;
#endif
#if LV_USE_TABLE
lv_style_t table_cell;
#endif
#if LV_USE_METER
lv_style_t meter_marker, meter_indic;
#endif
#if LV_USE_TEXTAREA
lv_style_t ta_cursor, ta_placeholder;
#endif
#if LV_USE_CALENDAR
lv_style_t calendar_btnm_bg, calendar_btnm_day, calendar_header;
#endif
#if LV_USE_MENU
lv_style_t menu_bg, menu_cont, menu_sidebar_cont, menu_main_cont, menu_page, menu_header_cont, menu_header_btn,
menu_section, menu_pressed, menu_separator;
#endif
#if LV_USE_MSGBOX
lv_style_t msgbox_bg, msgbox_button_bg, msgbox_backdrop_bg;
#endif
#if LV_USE_KEYBOARD
lv_style_t keyboard_button_bg;
#endif
#if LV_USE_LIST
lv_style_t list_bg, list_btn, list_item_grow, list_label;
#endif
#if LV_USE_TABVIEW
lv_style_t tab_bg_focus, tab_btn;
#endif
#if LV_USE_LED
lv_style_t led;
#endif
#if LV_USE_SCALE
lv_style_t scale;
#endif
} my_theme_styles_t;
typedef enum {
DISP_SMALL = 3,
DISP_MEDIUM = 2,
DISP_LARGE = 1,
} disp_size_t;
typedef struct _my_theme_t {
lv_theme_t base;
disp_size_t disp_size;
int32_t disp_dpi;
lv_color_t color_scr;
lv_color_t color_text;
lv_color_t color_card;
lv_color_t color_grey;
bool inited;
my_theme_styles_t styles;
lv_color_filter_dsc_t dark_filter;
lv_color_filter_dsc_t grey_filter;
#if LV_THEME_DEFAULT_TRANSITION_TIME
lv_style_transition_dsc_t trans_delayed;
lv_style_transition_dsc_t trans_normal;
#endif
} my_theme_t;
/**********************
* STATIC PROTOTYPES
**********************/
static void theme_apply(lv_theme_t * th, lv_obj_t * obj);
static void style_init_reset(lv_style_t * style);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* STATIC FUNCTIONS
**********************/
static lv_color_t dark_color_filter_cb(const lv_color_filter_dsc_t * f, lv_color_t c, lv_opa_t opa)
{
LV_UNUSED(f);
return lv_color_darken(c, opa);
}
static lv_color_t grey_filter_cb(const lv_color_filter_dsc_t * f, lv_color_t color, lv_opa_t opa)
{
LV_UNUSED(f);
if(theme_def->base.flags & MODE_DARK) return lv_color_mix(lv_palette_darken(LV_PALETTE_GREY, 2), color, opa);
else return lv_color_mix(lv_palette_lighten(LV_PALETTE_GREY, 2), color, opa);
}
static void style_init(struct _my_theme_t * theme)
{
#if TRANSITION_TIME
static const lv_style_prop_t trans_props[] = {
LV_STYLE_BG_OPA, LV_STYLE_BG_COLOR,
LV_STYLE_TRANSFORM_WIDTH, LV_STYLE_TRANSFORM_HEIGHT,
LV_STYLE_TRANSLATE_Y, LV_STYLE_TRANSLATE_X,
LV_STYLE_TRANSFORM_ROTATION,
LV_STYLE_TRANSFORM_SCALE_X, LV_STYLE_TRANSFORM_SCALE_Y,
LV_STYLE_COLOR_FILTER_OPA, LV_STYLE_COLOR_FILTER_DSC,
0
};
#endif
theme->color_scr = theme->base.flags & MODE_DARK ? DARK_COLOR_SCR : LIGHT_COLOR_SCR;
theme->color_text = theme->base.flags & MODE_DARK ? DARK_COLOR_TEXT : LIGHT_COLOR_TEXT;
theme->color_card = theme->base.flags & MODE_DARK ? DARK_COLOR_CARD : LIGHT_COLOR_CARD;
theme->color_grey = theme->base.flags & MODE_DARK ? DARK_COLOR_GREY : LIGHT_COLOR_GREY;
style_init_reset(&theme->styles.transition_delayed);
style_init_reset(&theme->styles.transition_normal);
#if TRANSITION_TIME
lv_style_transition_dsc_init(&theme->trans_delayed, trans_props, lv_anim_path_linear, TRANSITION_TIME, 70, NULL);
lv_style_transition_dsc_init(&theme->trans_normal, trans_props, lv_anim_path_linear, TRANSITION_TIME, 0, NULL);
lv_style_set_transition(&theme->styles.transition_delayed,
&theme->trans_delayed); /*Go back to default state with delay*/
lv_style_set_transition(&theme->styles.transition_normal, &theme->trans_normal); /*Go back to default state with delay*/
#endif
style_init_reset(&theme->styles.scrollbar);
lv_color_t sb_color = (theme->base.flags & MODE_DARK) ? lv_palette_darken(LV_PALETTE_GREY,
2) : lv_palette_main(LV_PALETTE_GREY);
lv_style_set_bg_color(&theme->styles.scrollbar, sb_color);
lv_style_set_radius(&theme->styles.scrollbar, LV_RADIUS_CIRCLE);
lv_style_set_pad_all(&theme->styles.scrollbar, _LV_DPX_CALC(theme->disp_dpi, 7));
lv_style_set_width(&theme->styles.scrollbar, _LV_DPX_CALC(theme->disp_dpi, 5));
lv_style_set_bg_opa(&theme->styles.scrollbar, LV_OPA_40);
#if TRANSITION_TIME
lv_style_set_transition(&theme->styles.scrollbar, &theme->trans_normal);
#endif
style_init_reset(&theme->styles.scrollbar_scrolled);
lv_style_set_bg_opa(&theme->styles.scrollbar_scrolled, LV_OPA_COVER);
style_init_reset(&theme->styles.scr);
lv_style_set_bg_opa(&theme->styles.scr, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.scr, theme->color_scr);
lv_style_set_text_color(&theme->styles.scr, theme->color_text);
lv_style_set_text_font(&theme->styles.scr, theme->base.font_normal);
lv_style_set_pad_row(&theme->styles.scr, PAD_SMALL);
lv_style_set_pad_column(&theme->styles.scr, PAD_SMALL);
style_init_reset(&theme->styles.card);
lv_style_set_radius(&theme->styles.card, RADIUS_DEFAULT);
lv_style_set_bg_opa(&theme->styles.card, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.card, theme->color_card);
lv_style_set_border_color(&theme->styles.card, theme->color_grey);
lv_style_set_border_width(&theme->styles.card, BORDER_WIDTH);
lv_style_set_border_post(&theme->styles.card, true);
lv_style_set_text_color(&theme->styles.card, theme->color_text);
lv_style_set_pad_all(&theme->styles.card, PAD_DEF);
lv_style_set_pad_row(&theme->styles.card, PAD_SMALL);
lv_style_set_pad_column(&theme->styles.card, PAD_SMALL);
lv_style_set_line_color(&theme->styles.card, lv_palette_main(LV_PALETTE_GREY));
lv_style_set_line_width(&theme->styles.card, _LV_DPX_CALC(theme->disp_dpi, 1));
style_init_reset(&theme->styles.outline_primary);
lv_style_set_outline_color(&theme->styles.outline_primary, theme->base.color_primary);
lv_style_set_outline_width(&theme->styles.outline_primary, OUTLINE_WIDTH);
lv_style_set_outline_pad(&theme->styles.outline_primary, OUTLINE_WIDTH);
lv_style_set_outline_opa(&theme->styles.outline_primary, LV_OPA_50);
style_init_reset(&theme->styles.outline_secondary);
lv_style_set_outline_color(&theme->styles.outline_secondary, theme->base.color_secondary);
lv_style_set_outline_width(&theme->styles.outline_secondary, OUTLINE_WIDTH);
lv_style_set_outline_opa(&theme->styles.outline_secondary, LV_OPA_50);
style_init_reset(&theme->styles.btn);
lv_style_set_radius(&theme->styles.btn,
_LV_DPX_CALC(theme->disp_dpi, theme->disp_size == DISP_LARGE ? 16 : theme->disp_size == DISP_MEDIUM ? 12 : 8));
lv_style_set_bg_opa(&theme->styles.btn, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.btn, theme->color_grey);
if(!(theme->base.flags & MODE_DARK)) {
lv_style_set_shadow_color(&theme->styles.btn, lv_palette_main(LV_PALETTE_GREY));
lv_style_set_shadow_width(&theme->styles.btn, LV_DPX(3));
lv_style_set_shadow_opa(&theme->styles.btn, LV_OPA_50);
lv_style_set_shadow_offset_y(&theme->styles.btn, _LV_DPX_CALC(theme->disp_dpi, LV_DPX(4)));
}
lv_style_set_text_color(&theme->styles.btn, theme->color_text);
lv_style_set_pad_hor(&theme->styles.btn, PAD_DEF);
lv_style_set_pad_ver(&theme->styles.btn, PAD_SMALL);
lv_style_set_pad_column(&theme->styles.btn, _LV_DPX_CALC(theme->disp_dpi, 5));
lv_style_set_pad_row(&theme->styles.btn, _LV_DPX_CALC(theme->disp_dpi, 5));
lv_color_filter_dsc_init(&theme->dark_filter, dark_color_filter_cb);
lv_color_filter_dsc_init(&theme->grey_filter, grey_filter_cb);
style_init_reset(&theme->styles.pressed);
lv_style_set_color_filter_dsc(&theme->styles.pressed, &theme->dark_filter);
lv_style_set_color_filter_opa(&theme->styles.pressed, 35);
style_init_reset(&theme->styles.disabled);
lv_style_set_color_filter_dsc(&theme->styles.disabled, &theme->grey_filter);
lv_style_set_color_filter_opa(&theme->styles.disabled, LV_OPA_50);
style_init_reset(&theme->styles.clip_corner);
lv_style_set_clip_corner(&theme->styles.clip_corner, true);
lv_style_set_border_post(&theme->styles.clip_corner, true);
style_init_reset(&theme->styles.pad_normal);
lv_style_set_pad_all(&theme->styles.pad_normal, PAD_DEF);
lv_style_set_pad_row(&theme->styles.pad_normal, PAD_DEF);
lv_style_set_pad_column(&theme->styles.pad_normal, PAD_DEF);
style_init_reset(&theme->styles.pad_small);
lv_style_set_pad_all(&theme->styles.pad_small, PAD_SMALL);
lv_style_set_pad_gap(&theme->styles.pad_small, PAD_SMALL);
style_init_reset(&theme->styles.pad_gap);
lv_style_set_pad_row(&theme->styles.pad_gap, _LV_DPX_CALC(theme->disp_dpi, 10));
lv_style_set_pad_column(&theme->styles.pad_gap, _LV_DPX_CALC(theme->disp_dpi, 10));
style_init_reset(&theme->styles.line_space_large);
lv_style_set_text_line_space(&theme->styles.line_space_large, _LV_DPX_CALC(theme->disp_dpi, 20));
style_init_reset(&theme->styles.text_align_center);
lv_style_set_text_align(&theme->styles.text_align_center, LV_TEXT_ALIGN_CENTER);
style_init_reset(&theme->styles.pad_zero);
lv_style_set_pad_all(&theme->styles.pad_zero, 0);
lv_style_set_pad_row(&theme->styles.pad_zero, 0);
lv_style_set_pad_column(&theme->styles.pad_zero, 0);
style_init_reset(&theme->styles.pad_tiny);
lv_style_set_pad_all(&theme->styles.pad_tiny, PAD_TINY);
lv_style_set_pad_row(&theme->styles.pad_tiny, PAD_TINY);
lv_style_set_pad_column(&theme->styles.pad_tiny, PAD_TINY);
style_init_reset(&theme->styles.bg_color_primary);
lv_style_set_bg_color(&theme->styles.bg_color_primary, theme->base.color_primary);
lv_style_set_text_color(&theme->styles.bg_color_primary, lv_color_white());
lv_style_set_bg_opa(&theme->styles.bg_color_primary, LV_OPA_COVER);
style_init_reset(&theme->styles.bg_color_primary_muted);
lv_style_set_bg_color(&theme->styles.bg_color_primary_muted, theme->base.color_primary);
lv_style_set_text_color(&theme->styles.bg_color_primary_muted, theme->base.color_primary);
lv_style_set_bg_opa(&theme->styles.bg_color_primary_muted, LV_OPA_20);
style_init_reset(&theme->styles.bg_color_secondary);
lv_style_set_bg_color(&theme->styles.bg_color_secondary, theme->base.color_secondary);
lv_style_set_text_color(&theme->styles.bg_color_secondary, lv_color_white());
lv_style_set_bg_opa(&theme->styles.bg_color_secondary, LV_OPA_COVER);
style_init_reset(&theme->styles.bg_color_secondary_muted);
lv_style_set_bg_color(&theme->styles.bg_color_secondary_muted, theme->base.color_secondary);
lv_style_set_text_color(&theme->styles.bg_color_secondary_muted, theme->base.color_secondary);
lv_style_set_bg_opa(&theme->styles.bg_color_secondary_muted, LV_OPA_20);
style_init_reset(&theme->styles.bg_color_grey);
lv_style_set_bg_color(&theme->styles.bg_color_grey, theme->color_grey);
lv_style_set_bg_opa(&theme->styles.bg_color_grey, LV_OPA_COVER);
lv_style_set_text_color(&theme->styles.bg_color_grey, theme->color_text);
style_init_reset(&theme->styles.bg_color_white);
lv_style_set_bg_color(&theme->styles.bg_color_white, theme->color_card);
lv_style_set_bg_opa(&theme->styles.bg_color_white, LV_OPA_COVER);
lv_style_set_text_color(&theme->styles.bg_color_white, theme->color_text);
style_init_reset(&theme->styles.circle);
lv_style_set_radius(&theme->styles.circle, LV_RADIUS_CIRCLE);
style_init_reset(&theme->styles.no_radius);
lv_style_set_radius(&theme->styles.no_radius, 0);
#if LV_THEME_DEFAULT_GROW
style_init_reset(&theme->styles.grow);
lv_style_set_transform_width(&theme->styles.grow, _LV_DPX_CALC(theme->disp_dpi, 3));
lv_style_set_transform_height(&theme->styles.grow, _LV_DPX_CALC(theme->disp_dpi, 3));
#endif
style_init_reset(&theme->styles.knob);
lv_style_set_bg_color(&theme->styles.knob, theme->base.color_primary);
lv_style_set_bg_opa(&theme->styles.knob, LV_OPA_COVER);
lv_style_set_pad_all(&theme->styles.knob, _LV_DPX_CALC(theme->disp_dpi, 6));
lv_style_set_radius(&theme->styles.knob, LV_RADIUS_CIRCLE);
style_init_reset(&theme->styles.anim);
lv_style_set_anim_time(&theme->styles.anim, 200);
style_init_reset(&theme->styles.anim_fast);
lv_style_set_anim_time(&theme->styles.anim_fast, 120);
#if LV_USE_ARC
style_init_reset(&theme->styles.arc_indic);
lv_style_set_arc_color(&theme->styles.arc_indic, theme->color_grey);
lv_style_set_arc_width(&theme->styles.arc_indic, _LV_DPX_CALC(theme->disp_dpi, 15));
lv_style_set_arc_rounded(&theme->styles.arc_indic, true);
style_init_reset(&theme->styles.arc_indic_primary);
lv_style_set_arc_color(&theme->styles.arc_indic_primary, theme->base.color_primary);
#endif
#if LV_USE_DROPDOWN
style_init_reset(&theme->styles.dropdown_list);
lv_style_set_max_height(&theme->styles.dropdown_list, LV_DPI_DEF * 2);
#endif
#if LV_USE_CHECKBOX
style_init_reset(&theme->styles.cb_marker);
lv_style_set_pad_all(&theme->styles.cb_marker, _LV_DPX_CALC(theme->disp_dpi, 3));
lv_style_set_border_width(&theme->styles.cb_marker, BORDER_WIDTH);
lv_style_set_border_color(&theme->styles.cb_marker, theme->base.color_primary);
lv_style_set_bg_color(&theme->styles.cb_marker, theme->color_card);
lv_style_set_bg_opa(&theme->styles.cb_marker, LV_OPA_COVER);
lv_style_set_radius(&theme->styles.cb_marker, RADIUS_DEFAULT / 2);
style_init_reset(&theme->styles.cb_marker_checked);
lv_style_set_bg_image_src(&theme->styles.cb_marker_checked, LV_SYMBOL_OK);
lv_style_set_text_color(&theme->styles.cb_marker_checked, lv_color_white());
lv_style_set_text_font(&theme->styles.cb_marker_checked, theme->base.font_small);
#endif
#if LV_USE_SWITCH
style_init_reset(&theme->styles.switch_knob);
lv_style_set_pad_all(&theme->styles.switch_knob, - _LV_DPX_CALC(theme->disp_dpi, 4));
lv_style_set_bg_color(&theme->styles.switch_knob, lv_color_white());
#endif
#if LV_USE_LINE
style_init_reset(&theme->styles.line);
lv_style_set_line_width(&theme->styles.line, 1);
lv_style_set_line_color(&theme->styles.line, theme->color_text);
#endif
#if LV_USE_CHART
style_init_reset(&theme->styles.chart_bg);
lv_style_set_border_post(&theme->styles.chart_bg, false);
lv_style_set_pad_column(&theme->styles.chart_bg, _LV_DPX_CALC(theme->disp_dpi, 10));
lv_style_set_line_color(&theme->styles.chart_bg, theme->color_grey);
style_init_reset(&theme->styles.chart_series);
lv_style_set_line_width(&theme->styles.chart_series, _LV_DPX_CALC(theme->disp_dpi, 3));
lv_style_set_radius(&theme->styles.chart_series, _LV_DPX_CALC(theme->disp_dpi, 3));
int32_t chart_size = _LV_DPX_CALC(theme->disp_dpi, 8);
lv_style_set_size(&theme->styles.chart_series, chart_size, chart_size);
lv_style_set_pad_column(&theme->styles.chart_series, _LV_DPX_CALC(theme->disp_dpi, 2));
style_init_reset(&theme->styles.chart_indic);
lv_style_set_radius(&theme->styles.chart_indic, LV_RADIUS_CIRCLE);
lv_style_set_size(&theme->styles.chart_indic, chart_size, chart_size);
lv_style_set_bg_color(&theme->styles.chart_indic, theme->base.color_primary);
lv_style_set_bg_opa(&theme->styles.chart_indic, LV_OPA_COVER);
#endif
#if LV_USE_MENU
style_init_reset(&theme->styles.menu_bg);
lv_style_set_pad_all(&theme->styles.menu_bg, 0);
lv_style_set_pad_gap(&theme->styles.menu_bg, 0);
lv_style_set_radius(&theme->styles.menu_bg, 0);
lv_style_set_clip_corner(&theme->styles.menu_bg, true);
lv_style_set_border_side(&theme->styles.menu_bg, LV_BORDER_SIDE_NONE);
style_init_reset(&theme->styles.menu_section);
lv_style_set_radius(&theme->styles.menu_section, RADIUS_DEFAULT);
lv_style_set_clip_corner(&theme->styles.menu_section, true);
lv_style_set_bg_opa(&theme->styles.menu_section, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.menu_section, theme->color_card);
lv_style_set_text_color(&theme->styles.menu_section, theme->color_text);
style_init_reset(&theme->styles.menu_cont);
lv_style_set_pad_hor(&theme->styles.menu_cont, PAD_SMALL);
lv_style_set_pad_ver(&theme->styles.menu_cont, PAD_SMALL);
lv_style_set_pad_gap(&theme->styles.menu_cont, PAD_SMALL);
lv_style_set_border_width(&theme->styles.menu_cont, _LV_DPX_CALC(theme->disp_dpi, 1));
lv_style_set_border_opa(&theme->styles.menu_cont, LV_OPA_10);
lv_style_set_border_color(&theme->styles.menu_cont, theme->color_text);
lv_style_set_border_side(&theme->styles.menu_cont, LV_BORDER_SIDE_NONE);
style_init_reset(&theme->styles.menu_sidebar_cont);
lv_style_set_pad_all(&theme->styles.menu_sidebar_cont, 0);
lv_style_set_pad_gap(&theme->styles.menu_sidebar_cont, 0);
lv_style_set_border_width(&theme->styles.menu_sidebar_cont, _LV_DPX_CALC(theme->disp_dpi, 1));
lv_style_set_border_opa(&theme->styles.menu_sidebar_cont, LV_OPA_10);
lv_style_set_border_color(&theme->styles.menu_sidebar_cont, theme->color_text);
lv_style_set_border_side(&theme->styles.menu_sidebar_cont, LV_BORDER_SIDE_RIGHT);
style_init_reset(&theme->styles.menu_main_cont);
lv_style_set_pad_all(&theme->styles.menu_main_cont, 0);
lv_style_set_pad_gap(&theme->styles.menu_main_cont, 0);
style_init_reset(&theme->styles.menu_header_cont);
lv_style_set_pad_hor(&theme->styles.menu_header_cont, PAD_SMALL);
lv_style_set_pad_ver(&theme->styles.menu_header_cont, PAD_TINY);
lv_style_set_pad_gap(&theme->styles.menu_header_cont, PAD_SMALL);
style_init_reset(&theme->styles.menu_header_btn);
lv_style_set_pad_hor(&theme->styles.menu_header_btn, PAD_TINY);
lv_style_set_pad_ver(&theme->styles.menu_header_btn, PAD_TINY);
lv_style_set_shadow_opa(&theme->styles.menu_header_btn, LV_OPA_TRANSP);
lv_style_set_bg_opa(&theme->styles.menu_header_btn, LV_OPA_TRANSP);
lv_style_set_text_color(&theme->styles.menu_header_btn, theme->color_text);
style_init_reset(&theme->styles.menu_page);
lv_style_set_pad_hor(&theme->styles.menu_page, 0);
lv_style_set_pad_gap(&theme->styles.menu_page, 0);
style_init_reset(&theme->styles.menu_pressed);
lv_style_set_bg_opa(&theme->styles.menu_pressed, LV_OPA_20);
lv_style_set_bg_color(&theme->styles.menu_pressed, lv_palette_main(LV_PALETTE_GREY));
style_init_reset(&theme->styles.menu_separator);
lv_style_set_bg_opa(&theme->styles.menu_separator, LV_OPA_TRANSP);
lv_style_set_pad_ver(&theme->styles.menu_separator, PAD_TINY);
#endif
#if LV_USE_METER
style_init_reset(&theme->styles.meter_marker);
lv_style_set_line_width(&theme->styles.meter_marker, _LV_DPX_CALC(theme->disp_dpi, 5));
lv_style_set_line_color(&theme->styles.meter_marker, theme->color_text);
int32_t meter_size = _LV_DPX_CALC(theme->disp_dpi, 20);
lv_style_set_size(&theme->styles.meter_marker, meter_size, meter_size);
meter_size = _LV_DPX_CALC(theme->disp_dpi, 15);
lv_style_set_pad_left(&theme->styles.meter_marker, meter_size);
style_init_reset(&theme->styles.meter_indic);
lv_style_set_radius(&theme->styles.meter_indic, LV_RADIUS_CIRCLE);
lv_style_set_bg_color(&theme->styles.meter_indic, theme->color_text);
lv_style_set_bg_opa(&theme->styles.meter_indic, LV_OPA_COVER);
lv_style_set_size(&theme->styles.meter_indic, meter_size, meter_size);
#endif
#if LV_USE_TABLE
style_init_reset(&theme->styles.table_cell);
lv_style_set_border_width(&theme->styles.table_cell, _LV_DPX_CALC(theme->disp_dpi, 1));
lv_style_set_border_color(&theme->styles.table_cell, theme->color_grey);
lv_style_set_border_side(&theme->styles.table_cell, LV_BORDER_SIDE_TOP | LV_BORDER_SIDE_BOTTOM);
#endif
#if LV_USE_TEXTAREA
style_init_reset(&theme->styles.ta_cursor);
lv_style_set_border_color(&theme->styles.ta_cursor, theme->color_text);
lv_style_set_border_width(&theme->styles.ta_cursor, _LV_DPX_CALC(theme->disp_dpi, 2));
lv_style_set_pad_left(&theme->styles.ta_cursor, - _LV_DPX_CALC(theme->disp_dpi, 1));
lv_style_set_border_side(&theme->styles.ta_cursor, LV_BORDER_SIDE_LEFT);
lv_style_set_anim_time(&theme->styles.ta_cursor, 400);
style_init_reset(&theme->styles.ta_placeholder);
lv_style_set_text_color(&theme->styles.ta_placeholder,
(theme->base.flags & MODE_DARK) ? lv_palette_darken(LV_PALETTE_GREY,
2) : lv_palette_lighten(LV_PALETTE_GREY, 1));
#endif
#if LV_USE_CALENDAR
style_init_reset(&theme->styles.calendar_btnm_bg);
lv_style_set_pad_all(&theme->styles.calendar_btnm_bg, PAD_SMALL);
lv_style_set_pad_gap(&theme->styles.calendar_btnm_bg, PAD_SMALL / 2);
style_init_reset(&theme->styles.calendar_btnm_day);
lv_style_set_border_width(&theme->styles.calendar_btnm_day, _LV_DPX_CALC(theme->disp_dpi, 1));
lv_style_set_border_color(&theme->styles.calendar_btnm_day, theme->color_grey);
lv_style_set_bg_color(&theme->styles.calendar_btnm_day, theme->color_card);
lv_style_set_bg_opa(&theme->styles.calendar_btnm_day, LV_OPA_20);
style_init_reset(&theme->styles.calendar_header);
lv_style_set_pad_hor(&theme->styles.calendar_header, PAD_SMALL);
lv_style_set_pad_top(&theme->styles.calendar_header, PAD_SMALL);
lv_style_set_pad_bottom(&theme->styles.calendar_header, PAD_TINY);
lv_style_set_pad_gap(&theme->styles.calendar_header, PAD_SMALL);
#endif
#if LV_USE_MSGBOX
/*To add space for for the button shadow*/
style_init_reset(&theme->styles.msgbox_button_bg);
lv_style_set_pad_all(&theme->styles.msgbox_button_bg, _LV_DPX_CALC(theme->disp_dpi, 4));
style_init_reset(&theme->styles.msgbox_bg);
lv_style_set_max_width(&theme->styles.msgbox_bg, lv_pct(100));
style_init_reset(&theme->styles.msgbox_backdrop_bg);
lv_style_set_bg_color(&theme->styles.msgbox_backdrop_bg, lv_palette_main(LV_PALETTE_GREY));
lv_style_set_bg_opa(&theme->styles.msgbox_backdrop_bg, LV_OPA_100);
#endif
#if LV_USE_KEYBOARD
style_init_reset(&theme->styles.keyboard_button_bg);
lv_style_set_shadow_width(&theme->styles.keyboard_button_bg, 0);
lv_style_set_radius(&theme->styles.keyboard_button_bg,
theme->disp_size == DISP_SMALL ? RADIUS_DEFAULT / 2 : RADIUS_DEFAULT);
#endif
#if LV_USE_TABVIEW
style_init_reset(&theme->styles.tab_btn);
lv_style_set_border_color(&theme->styles.tab_btn, theme->base.color_primary);
lv_style_set_border_width(&theme->styles.tab_btn, BORDER_WIDTH * 2);
lv_style_set_border_side(&theme->styles.tab_btn, LV_BORDER_SIDE_BOTTOM);
style_init_reset(&theme->styles.tab_bg_focus);
lv_style_set_outline_pad(&theme->styles.tab_bg_focus, -BORDER_WIDTH);
#endif
#if LV_USE_LIST
style_init_reset(&theme->styles.list_bg);
lv_style_set_pad_hor(&theme->styles.list_bg, PAD_DEF);
lv_style_set_pad_ver(&theme->styles.list_bg, 0);
lv_style_set_pad_gap(&theme->styles.list_bg, 0);
lv_style_set_clip_corner(&theme->styles.list_bg, true);
style_init_reset(&theme->styles.list_btn);
lv_style_set_border_width(&theme->styles.list_btn, _LV_DPX_CALC(theme->disp_dpi, 1));
lv_style_set_border_color(&theme->styles.list_btn, theme->color_grey);
lv_style_set_border_side(&theme->styles.list_btn, LV_BORDER_SIDE_BOTTOM);
lv_style_set_pad_all(&theme->styles.list_btn, PAD_SMALL);
lv_style_set_pad_column(&theme->styles.list_btn, PAD_SMALL);
style_init_reset(&theme->styles.list_item_grow);
lv_style_set_transform_width(&theme->styles.list_item_grow, PAD_DEF);
#endif
#if LV_USE_LED
style_init_reset(&theme->styles.led);
lv_style_set_bg_opa(&theme->styles.led, LV_OPA_COVER);
lv_style_set_bg_color(&theme->styles.led, lv_color_white());
lv_style_set_bg_grad_color(&theme->styles.led, lv_palette_main(LV_PALETTE_GREY));
lv_style_set_radius(&theme->styles.led, LV_RADIUS_CIRCLE);
lv_style_set_shadow_width(&theme->styles.led, _LV_DPX_CALC(theme->disp_dpi, 15));
lv_style_set_shadow_color(&theme->styles.led, lv_color_white());
lv_style_set_shadow_spread(&theme->styles.led, _LV_DPX_CALC(theme->disp_dpi, 5));
#endif
#if LV_USE_SCALE
style_init_reset(&theme->styles.scale);
lv_style_set_line_color(&theme->styles.scale, theme->color_text);
lv_style_set_line_width(&theme->styles.scale, LV_DPX(2));
lv_style_set_arc_color(&theme->styles.scale, theme->color_text);
lv_style_set_arc_width(&theme->styles.scale, LV_DPX(2));
#endif
}
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_theme_t * lv_theme_default_init(lv_display_t * disp, lv_color_t color_primary, lv_color_t color_secondary, bool dark,
const lv_font_t * font)
{
/*This trick is required only to avoid the garbage collection of
*styles' data if LVGL is used in a binding (e.g. Micropython)
*In a general case styles could be in a simple `static lv_style_t my_style...` variables*/
if(!lv_theme_default_is_inited()) {
theme_def = (my_theme_t *)lv_malloc(sizeof(my_theme_t));
lv_memzero(theme_def, sizeof(my_theme_t));
}
struct _my_theme_t * theme = theme_def;
lv_display_t * new_disp = disp == NULL ? lv_display_get_default() : disp;
int32_t new_dpi = lv_display_get_dpi(new_disp);
int32_t hor_res = lv_display_get_horizontal_resolution(new_disp);
disp_size_t new_size;
if(hor_res <= 320) new_size = DISP_SMALL;
else if(hor_res < 720) new_size = DISP_MEDIUM;
else new_size = DISP_LARGE;
/* check theme information whether will change or not*/
if(theme->inited && theme->disp_dpi == new_dpi &&
theme->disp_size == new_size &&
lv_color_eq(theme->base.color_primary, color_primary) &&
lv_color_eq(theme->base.color_secondary, color_secondary) &&
theme->base.flags == dark ? MODE_DARK : 0 &&
theme->base.font_small == font) {
return (lv_theme_t *) theme;
}
theme->disp_size = new_size;
theme->disp_dpi = new_dpi;
theme->base.disp = new_disp;
theme->base.color_primary = color_primary;
theme->base.color_secondary = color_secondary;
theme->base.font_small = font;
theme->base.font_normal = font;
theme->base.font_large = font;
theme->base.apply_cb = theme_apply;
theme->base.flags = dark ? MODE_DARK : 0;
style_init(theme);
if(disp == NULL || lv_display_get_theme(disp) == (lv_theme_t *)theme) lv_obj_report_style_change(NULL);
theme->inited = true;
return (lv_theme_t *) theme;
}
void lv_theme_default_deinit(void)
{
if(theme_def) {
lv_free(theme_def);
theme_def = NULL;
}
}
lv_theme_t * lv_theme_default_get(void)
{
if(!lv_theme_default_is_inited()) {
return NULL;
}
return (lv_theme_t *)theme_def;
}
bool lv_theme_default_is_inited(void)
{
struct _my_theme_t * theme = theme_def;
if(theme == NULL) return false;
return theme->inited;
}
static void theme_apply(lv_theme_t * th, lv_obj_t * obj)
{
LV_UNUSED(th);
struct _my_theme_t * theme = theme_def;
if(lv_obj_get_parent(obj) == NULL) {
lv_obj_add_style(obj, &theme->styles.scr, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
return;
}
if(lv_obj_check_type(obj, &lv_obj_class)) {
#if LV_USE_TABVIEW
lv_obj_t * parent = lv_obj_get_parent(obj);
/*Tabview content area*/
if(lv_obj_check_type(parent, &lv_tabview_class)) {
return;
}
/*Tabview pages*/
else if(lv_obj_check_type(lv_obj_get_parent(parent), &lv_tabview_class)) {
lv_obj_add_style(obj, &theme->styles.pad_normal, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
return;
}
#endif
#if LV_USE_WIN
/*Header*/
if(lv_obj_get_index(obj) == 0 && lv_obj_check_type(lv_obj_get_parent(obj), &lv_win_class)) {
lv_obj_add_style(obj, &theme->styles.bg_color_grey, 0);
lv_obj_add_style(obj, &theme->styles.pad_tiny, 0);
return;
}
/*Content*/
else if(lv_obj_get_index(obj) == 1 && lv_obj_check_type(lv_obj_get_parent(obj), &lv_win_class)) {
lv_obj_add_style(obj, &theme->styles.scr, 0);
lv_obj_add_style(obj, &theme->styles.pad_normal, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
return;
}
#endif
#if LV_USE_CALENDAR
if(lv_obj_check_type(lv_obj_get_parent(obj), &lv_calendar_class)) {
/*No style*/
return;
}
#endif
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
}
#if LV_USE_BTN
else if(lv_obj_check_type(obj, &lv_button_class)) {
lv_obj_add_style(obj, &theme->styles.btn, 0);
lv_obj_add_style(obj, &theme->styles.bg_color_primary, 0);
lv_obj_add_style(obj, &theme->styles.transition_delayed, 0);
lv_obj_add_style(obj, &theme->styles.pressed, LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.transition_normal, LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
#if LV_THEME_DEFAULT_GROW
lv_obj_add_style(obj, &theme->styles.grow, LV_STATE_PRESSED);
#endif
lv_obj_add_style(obj, &theme->styles.bg_color_secondary, LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.disabled, LV_STATE_DISABLED);
#if LV_USE_MENU
if(lv_obj_check_type(lv_obj_get_parent(obj), &lv_menu_sidebar_header_cont_class) ||
lv_obj_check_type(lv_obj_get_parent(obj), &lv_menu_main_header_cont_class)) {
lv_obj_add_style(obj, &theme->styles.menu_header_btn, 0);
lv_obj_add_style(obj, &theme->styles.menu_pressed, LV_STATE_PRESSED);
}
#endif
}
#endif
#if LV_USE_LINE
else if(lv_obj_check_type(obj, &lv_line_class)) {
lv_obj_add_style(obj, &theme->styles.line, 0);
}
#endif
#if LV_USE_BTNMATRIX
else if(lv_obj_check_type(obj, &lv_buttonmatrix_class)) {
#if LV_USE_MSGBOX
if(lv_obj_check_type(lv_obj_get_parent(obj), &lv_msgbox_class)) {
lv_obj_add_style(obj, &theme->styles.msgbox_button_bg, 0);
lv_obj_add_style(obj, &theme->styles.pad_gap, 0);
lv_obj_add_style(obj, &theme->styles.btn, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.pressed, LV_PART_ITEMS | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.disabled, LV_PART_ITEMS | LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary, LV_PART_ITEMS | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary_muted, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.bg_color_secondary_muted, LV_PART_ITEMS | LV_STATE_EDITED);
return;
}
#endif
#if LV_USE_TABVIEW
if(lv_obj_check_type(lv_obj_get_parent(obj), &lv_tabview_class)) {
lv_obj_add_style(obj, &theme->styles.bg_color_white, 0);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.tab_bg_focus, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.pressed, LV_PART_ITEMS | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary_muted, LV_PART_ITEMS | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.tab_btn, LV_PART_ITEMS | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.outline_secondary, LV_PART_ITEMS | LV_STATE_EDITED);
lv_obj_add_style(obj, &theme->styles.tab_bg_focus, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
return;
}
#endif
#if LV_USE_CALENDAR
if(lv_obj_check_type(lv_obj_get_parent(obj), &lv_calendar_class)) {
lv_obj_add_style(obj, &theme->styles.calendar_btnm_bg, 0);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.outline_secondary, LV_STATE_EDITED);
lv_obj_add_style(obj, &theme->styles.calendar_btnm_day, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.pressed, LV_PART_ITEMS | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.disabled, LV_PART_ITEMS | LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.outline_secondary, LV_PART_ITEMS | LV_STATE_EDITED);
return;
}
#endif
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.outline_secondary, LV_STATE_EDITED);
lv_obj_add_style(obj, &theme->styles.btn, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.disabled, LV_PART_ITEMS | LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.pressed, LV_PART_ITEMS | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary, LV_PART_ITEMS | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.outline_secondary, LV_PART_ITEMS | LV_STATE_EDITED);
}
#endif
#if LV_USE_BAR
else if(lv_obj_check_type(obj, &lv_bar_class)) {
lv_obj_add_style(obj, &theme->styles.bg_color_primary_muted, 0);
lv_obj_add_style(obj, &theme->styles.circle, 0);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.outline_secondary, LV_STATE_EDITED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.circle, LV_PART_INDICATOR);
}
#endif
#if LV_USE_SLIDER
else if(lv_obj_check_type(obj, &lv_slider_class)) {
lv_obj_add_style(obj, &theme->styles.bg_color_primary_muted, 0);
lv_obj_add_style(obj, &theme->styles.circle, 0);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.outline_secondary, LV_STATE_EDITED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.circle, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.knob, LV_PART_KNOB);
#if LV_THEME_DEFAULT_GROW
lv_obj_add_style(obj, &theme->styles.grow, LV_PART_KNOB | LV_STATE_PRESSED);
#endif
lv_obj_add_style(obj, &theme->styles.transition_delayed, LV_PART_KNOB);
lv_obj_add_style(obj, &theme->styles.transition_normal, LV_PART_KNOB | LV_STATE_PRESSED);
}
#endif
#if LV_USE_TABLE
else if(lv_obj_check_type(obj, &lv_table_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.pad_zero, 0);
lv_obj_add_style(obj, &theme->styles.no_radius, 0);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.outline_secondary, LV_STATE_EDITED);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
lv_obj_add_style(obj, &theme->styles.bg_color_white, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.table_cell, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.pad_normal, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.pressed, LV_PART_ITEMS | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.bg_color_secondary, LV_PART_ITEMS | LV_STATE_EDITED);
}
#endif
#if LV_USE_CHECKBOX
else if(lv_obj_check_type(obj, &lv_checkbox_class)) {
lv_obj_add_style(obj, &theme->styles.pad_gap, 0);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.disabled, LV_PART_INDICATOR | LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.cb_marker, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.bg_color_primary, LV_PART_INDICATOR | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.cb_marker_checked, LV_PART_INDICATOR | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.pressed, LV_PART_INDICATOR | LV_STATE_PRESSED);
#if LV_THEME_DEFAULT_GROW
lv_obj_add_style(obj, &theme->styles.grow, LV_PART_INDICATOR | LV_STATE_PRESSED);
#endif
lv_obj_add_style(obj, &theme->styles.transition_normal, LV_PART_INDICATOR | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.transition_delayed, LV_PART_INDICATOR);
}
#endif
#if LV_USE_SWITCH
else if(lv_obj_check_type(obj, &lv_switch_class)) {
lv_obj_add_style(obj, &theme->styles.bg_color_grey, 0);
lv_obj_add_style(obj, &theme->styles.circle, 0);
lv_obj_add_style(obj, &theme->styles.anim_fast, 0);
lv_obj_add_style(obj, &theme->styles.disabled, LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.bg_color_primary, LV_PART_INDICATOR | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.circle, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.disabled, LV_PART_INDICATOR | LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.knob, LV_PART_KNOB);
lv_obj_add_style(obj, &theme->styles.bg_color_white, LV_PART_KNOB);
lv_obj_add_style(obj, &theme->styles.switch_knob, LV_PART_KNOB);
lv_obj_add_style(obj, &theme->styles.disabled, LV_PART_KNOB | LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.transition_normal, LV_PART_INDICATOR | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.transition_normal, LV_PART_INDICATOR);
}
#endif
#if LV_USE_CHART
else if(lv_obj_check_type(obj, &lv_chart_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.pad_small, 0);
lv_obj_add_style(obj, &theme->styles.chart_bg, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
lv_obj_add_style(obj, &theme->styles.chart_series, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.chart_indic, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.chart_series, LV_PART_CURSOR);
}
#endif
#if LV_USE_ROLLER
else if(lv_obj_check_type(obj, &lv_roller_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.anim, 0);
lv_obj_add_style(obj, &theme->styles.line_space_large, 0);
lv_obj_add_style(obj, &theme->styles.text_align_center, 0);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.outline_secondary, LV_STATE_EDITED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary, LV_PART_SELECTED);
}
#endif
#if LV_USE_DROPDOWN
else if(lv_obj_check_type(obj, &lv_dropdown_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.pad_small, 0);
lv_obj_add_style(obj, &theme->styles.transition_delayed, 0);
lv_obj_add_style(obj, &theme->styles.transition_normal, LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.pressed, LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.outline_secondary, LV_STATE_EDITED);
lv_obj_add_style(obj, &theme->styles.transition_normal, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.disabled, LV_STATE_DISABLED);
}
else if(lv_obj_check_type(obj, &lv_dropdownlist_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.clip_corner, 0);
lv_obj_add_style(obj, &theme->styles.line_space_large, 0);
lv_obj_add_style(obj, &theme->styles.dropdown_list, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
lv_obj_add_style(obj, &theme->styles.bg_color_white, LV_PART_SELECTED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary, LV_PART_SELECTED | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.pressed, LV_PART_SELECTED | LV_STATE_PRESSED);
}
#endif
#if LV_USE_ARC
else if(lv_obj_check_type(obj, &lv_arc_class)) {
lv_obj_add_style(obj, &theme->styles.arc_indic, 0);
lv_obj_add_style(obj, &theme->styles.arc_indic, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.arc_indic_primary, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.knob, LV_PART_KNOB);
}
#endif
#if LV_USE_SPINNER
else if(lv_obj_check_type(obj, &lv_spinner_class)) {
lv_obj_add_style(obj, &theme->styles.arc_indic, 0);
lv_obj_add_style(obj, &theme->styles.arc_indic, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.arc_indic_primary, LV_PART_INDICATOR);
}
#endif
//#if LV_USE_METER
// else if(lv_obj_check_type(obj, &lv_meter_class)) {
// lv_obj_add_style(obj, &theme->styles.card, 0);
// lv_obj_add_style(obj, &theme->styles.circle, 0);
// lv_obj_add_style(obj, &theme->styles.meter_indic, LV_PART_INDICATOR);
// }
//#endif
#if LV_USE_TEXTAREA
else if(lv_obj_check_type(obj, &lv_textarea_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.pad_small, 0);
lv_obj_add_style(obj, &theme->styles.disabled, LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.outline_secondary, LV_STATE_EDITED);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
lv_obj_add_style(obj, &theme->styles.ta_cursor, LV_PART_CURSOR | LV_STATE_FOCUSED);
lv_obj_add_style(obj, &theme->styles.ta_placeholder, LV_PART_TEXTAREA_PLACEHOLDER);
}
#endif
#if LV_USE_CALENDAR
else if(lv_obj_check_type(obj, &lv_calendar_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.pad_zero, 0);
}
#if LV_USE_CALENDAR_HEADER_ARROW
else if(lv_obj_check_type(obj, &lv_calendar_header_arrow_class)) {
lv_obj_add_style(obj, &theme->styles.calendar_header, 0);
}
#endif
#if LV_USE_CALENDAR_HEADER_DROPDOWN
else if(lv_obj_check_type(obj, &lv_calendar_header_dropdown_class)) {
lv_obj_add_style(obj, &theme->styles.calendar_header, 0);
}
#endif
#endif
#if LV_USE_KEYBOARD
else if(lv_obj_check_type(obj, &lv_keyboard_class)) {
lv_obj_add_style(obj, &theme->styles.scr, 0);
lv_obj_add_style(obj, theme->disp_size == DISP_LARGE ? &theme->styles.pad_small : &theme->styles.pad_tiny, 0);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.outline_secondary, LV_STATE_EDITED);
lv_obj_add_style(obj, &theme->styles.btn, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.disabled, LV_PART_ITEMS | LV_STATE_DISABLED);
lv_obj_add_style(obj, &theme->styles.bg_color_white, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.keyboard_button_bg, LV_PART_ITEMS);
lv_obj_add_style(obj, &theme->styles.pressed, LV_PART_ITEMS | LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.bg_color_grey, LV_PART_ITEMS | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary_muted, LV_PART_ITEMS | LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.bg_color_secondary_muted, LV_PART_ITEMS | LV_STATE_EDITED);
}
#endif
#if LV_USE_LIST
else if(lv_obj_check_type(obj, &lv_list_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.list_bg, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
return;
}
else if(lv_obj_check_type(obj, &lv_list_text_class)) {
lv_obj_add_style(obj, &theme->styles.bg_color_grey, 0);
lv_obj_add_style(obj, &theme->styles.list_item_grow, 0);
}
else if(lv_obj_check_type(obj, &lv_list_button_class)) {
lv_obj_add_style(obj, &theme->styles.bg_color_white, 0);
lv_obj_add_style(obj, &theme->styles.list_btn, 0);
lv_obj_add_style(obj, &theme->styles.bg_color_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.list_item_grow, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.list_item_grow, LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.pressed, LV_STATE_PRESSED);
}
#endif
#if LV_USE_MENU
else if(lv_obj_check_type(obj, &lv_menu_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.menu_bg, 0);
}
else if(lv_obj_check_type(obj, &lv_menu_sidebar_cont_class)) {
lv_obj_add_style(obj, &theme->styles.menu_sidebar_cont, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
}
else if(lv_obj_check_type(obj, &lv_menu_main_cont_class)) {
lv_obj_add_style(obj, &theme->styles.menu_main_cont, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
}
else if(lv_obj_check_type(obj, &lv_menu_cont_class)) {
lv_obj_add_style(obj, &theme->styles.menu_cont, 0);
lv_obj_add_style(obj, &theme->styles.menu_pressed, LV_STATE_PRESSED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary_muted, LV_STATE_PRESSED | LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary_muted, LV_STATE_CHECKED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary, LV_STATE_FOCUS_KEY);
}
else if(lv_obj_check_type(obj, &lv_menu_sidebar_header_cont_class) ||
lv_obj_check_type(obj, &lv_menu_main_header_cont_class)) {
lv_obj_add_style(obj, &theme->styles.menu_header_cont, 0);
}
else if(lv_obj_check_type(obj, &lv_menu_page_class)) {
lv_obj_add_style(obj, &theme->styles.menu_page, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
}
else if(lv_obj_check_type(obj, &lv_menu_section_class)) {
lv_obj_add_style(obj, &theme->styles.menu_section, 0);
}
else if(lv_obj_check_type(obj, &lv_menu_separator_class)) {
lv_obj_add_style(obj, &theme->styles.menu_separator, 0);
}
#endif
#if LV_USE_MSGBOX
else if(lv_obj_check_type(obj, &lv_msgbox_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.msgbox_bg, 0);
return;
}
else if(lv_obj_check_type(obj, &lv_msgbox_backdrop_class)) {
lv_obj_add_style(obj, &theme->styles.msgbox_backdrop_bg, 0);
}
#endif
#if LV_USE_SPINBOX
else if(lv_obj_check_type(obj, &lv_spinbox_class)) {
lv_obj_add_style(obj, &theme->styles.card, 0);
lv_obj_add_style(obj, &theme->styles.pad_small, 0);
lv_obj_add_style(obj, &theme->styles.outline_primary, LV_STATE_FOCUS_KEY);
lv_obj_add_style(obj, &theme->styles.outline_secondary, LV_STATE_EDITED);
lv_obj_add_style(obj, &theme->styles.bg_color_primary, LV_PART_CURSOR);
}
#endif
#if LV_USE_TILEVIEW
else if(lv_obj_check_type(obj, &lv_tileview_class)) {
lv_obj_add_style(obj, &theme->styles.scr, 0);
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
}
else if(lv_obj_check_type(obj, &lv_tileview_tile_class)) {
lv_obj_add_style(obj, &theme->styles.scrollbar, LV_PART_SCROLLBAR);
lv_obj_add_style(obj, &theme->styles.scrollbar_scrolled, LV_PART_SCROLLBAR | LV_STATE_SCROLLED);
}
#endif
#if LV_USE_TABVIEW
else if(lv_obj_check_type(obj, &lv_tabview_class)) {
lv_obj_add_style(obj, &theme->styles.scr, 0);
lv_obj_add_style(obj, &theme->styles.pad_zero, 0);
}
#endif
#if LV_USE_WIN
else if(lv_obj_check_type(obj, &lv_win_class)) {
lv_obj_add_style(obj, &theme->styles.clip_corner, 0);
}
#endif
#if LV_USE_LED
else if(lv_obj_check_type(obj, &lv_led_class)) {
lv_obj_add_style(obj, &theme->styles.led, 0);
}
#endif
#if LV_USE_SCALE
else if(lv_obj_check_type(obj, &lv_scale_class)) {
lv_obj_add_style(obj, &theme->styles.scale, LV_PART_MAIN);
lv_obj_add_style(obj, &theme->styles.scale, LV_PART_INDICATOR);
lv_obj_add_style(obj, &theme->styles.scale, LV_PART_ITEMS);
}
#endif
}
/**********************
* STATIC FUNCTIONS
**********************/
static void style_init_reset(lv_style_t * style)
{
if(theme_def->inited) {
lv_style_reset(style);
}
else {
lv_style_init(style);
}
}
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/table/lv_table.c | /**
* @file lv_table.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_table.h"
#if LV_USE_TABLE != 0
#include "../../indev/lv_indev.h"
#include "../../misc/lv_assert.h"
#include "../../misc/lv_text.h"
#include "../../misc/lv_text_ap.h"
#include "../../misc/lv_math.h"
#include "../../stdlib/lv_sprintf.h"
#include "../../draw/lv_draw.h"
#include "../../stdlib/lv_string.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 int32_t get_row_height(lv_obj_t * obj, uint32_t row_id, const lv_font_t * font,
int32_t letter_space, int32_t line_space,
int32_t cell_left, int32_t cell_right, int32_t cell_top, int32_t cell_bottom);
static void refr_size_form_row(lv_obj_t * obj, uint32_t start_row);
static void refr_cell_size(lv_obj_t * obj, uint32_t row, uint32_t col);
static lv_result_t get_pressed_cell(lv_obj_t * obj, uint32_t * row, uint32_t * col);
static size_t get_cell_txt_len(const char * txt);
static void copy_cell_txt(char * dst, const char * txt);
static void get_cell_area(lv_obj_t * obj, uint32_t row, uint32_t col, lv_area_t * area);
static void scroll_to_selected_cell(lv_obj_t * obj);
static inline bool is_cell_empty(void * cell)
{
return cell == NULL;
}
/**********************
* 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),
.name = "table",
};
/**********************
* 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, uint32_t row, uint32_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];
size_t to_allocate = get_cell_txt_len(txt);
table->cell_data[cell] = lv_realloc(table->cell_data[cell], to_allocate);
LV_ASSERT_MALLOC(table->cell_data[cell]);
if(table->cell_data[cell] == NULL) return;
copy_cell_txt(table->cell_data[cell], txt);
table->cell_data[cell][0] = ctrl;
refr_cell_size(obj, row, col);
}
void lv_table_set_cell_value_fmt(lv_obj_t * obj, uint32_t row, uint32_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_table_set_col_cnt(obj, col + 1);
}
/*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_malloc(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_text_ap_calc_bytes_cnt(raw_txt);
table->cell_data[cell] = lv_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_text_ap_proc(raw_txt, &table->cell_data[cell][1]);
lv_free(raw_txt);
#else
table->cell_data[cell] = lv_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;
refr_cell_size(obj, row, col);
}
void lv_table_set_row_cnt(lv_obj_t * obj, uint32_t row_cnt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_table_t * table = (lv_table_t *)obj;
if(table->row_cnt == row_cnt) return;
uint32_t old_row_cnt = table->row_cnt;
table->row_cnt = row_cnt;
table->row_h = lv_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) {
uint32_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_free(table->cell_data[i]);
}
}
table->cell_data = lv_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_memzero(&table->cell_data[old_cell_cnt], (new_cell_cnt - old_cell_cnt) * sizeof(table->cell_data[0]));
}
refr_size_form_row(obj, 0);
}
void lv_table_set_col_cnt(lv_obj_t * obj, uint32_t col_cnt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_table_t * table = (lv_table_t *)obj;
if(table->col_cnt == col_cnt) return;
uint32_t old_col_cnt = table->col_cnt;
table->col_cnt = col_cnt;
char ** new_cell_data = lv_malloc(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_memzero(new_cell_data, new_cell_cnt * sizeof(table->cell_data[0]));
/*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(&new_cell_data[new_col_start], &table->cell_data[old_col_start],
sizeof(new_cell_data[0]) * min_col_cnt);
/*Free the old cells (only if the table becomes smaller)*/
int32_t i;
for(i = 0; i < (int32_t)old_col_cnt - (int32_t)col_cnt; i++) {
uint32_t idx = old_col_start + min_col_cnt + i;
lv_free(table->cell_data[idx]);
table->cell_data[idx] = NULL;
}
}
lv_free(table->cell_data);
table->cell_data = new_cell_data;
/*Initialize the new column widths if any*/
table->col_w = lv_realloc(table->col_w, col_cnt * sizeof(table->col_w[0]));
LV_ASSERT_MALLOC(table->col_w);
if(table->col_w == NULL) return;
uint32_t col;
for(col = old_col_cnt; col < col_cnt; col++) {
table->col_w[col] = LV_DPI_DEF;
}
refr_size_form_row(obj, 0) ;
}
void lv_table_set_col_width(lv_obj_t * obj, uint32_t col_id, int32_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_form_row(obj, 0);
}
void lv_table_add_cell_ctrl(lv_obj_t * obj, uint32_t row, uint32_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(is_cell_empty(table->cell_data[cell])) {
table->cell_data[cell] = lv_malloc(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, uint32_t row, uint32_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(is_cell_empty(table->cell_data[cell])) {
table->cell_data[cell] = lv_malloc(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, uint32_t row, uint32_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("invalid row or column");
return "";
}
uint32_t cell = row * table->col_cnt + col;
if(is_cell_empty(table->cell_data[cell])) return "";
return &table->cell_data[cell][1]; /*Skip the format byte*/
}
uint32_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;
}
uint32_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;
}
int32_t lv_table_get_col_width(lv_obj_t * obj, uint32_t col)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_table_t * table = (lv_table_t *)obj;
if(col >= table->col_cnt) {
LV_LOG_WARN("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, uint32_t row, uint32_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("invalid row or column");
return false;
}
uint32_t cell = row * table->col_cnt + col;
if(is_cell_empty(table->cell_data[cell])) return false;
else return (table->cell_data[cell][0] & ctrl) == ctrl;
}
void lv_table_get_selected_cell(lv_obj_t * obj, uint32_t * row, uint32_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_malloc(table->col_cnt * sizeof(table->col_w[0]));
table->row_h = lv_malloc(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_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*/
uint32_t i;
for(i = 0; i < table->col_cnt * table->row_cnt; i++) {
if(table->cell_data[i]) {
lv_free(table->cell_data[i]);
table->cell_data[i] = NULL;
}
}
if(table->cell_data) lv_free(table->cell_data);
if(table->row_h) lv_free(table->row_h);
if(table->col_w) lv_free(table->col_w);
}
static void lv_table_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_result_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RESULT_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_form_row(obj, 0);
}
else if(code == LV_EVENT_GET_SELF_SIZE) {
lv_point_t * p = lv_event_get_param(e);
uint32_t i;
int32_t w = 0;
for(i = 0; i < table->col_cnt; i++) w += table->col_w[i];
int32_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) {
uint32_t col;
uint32_t row;
lv_result_t pr_res = get_pressed_cell(obj, &row, &col);
if(pr_res == LV_RESULT_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_active();
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_obj_send_event(obj, LV_EVENT_VALUE_CHANGED, NULL);
if(res != LV_RESULT_OK) return;
}
lv_indev_type_t indev_type = lv_indev_get_type(lv_indev_active());
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;
scroll_to_selected_cell(obj);
lv_obj_invalidate(obj);
return;
}
if(col >= (int32_t)table->col_cnt) col = 0;
if(row >= (int32_t)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 >= (int32_t)table->col_cnt) {
if(row < (int32_t)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 >= (int32_t)table->row_cnt) {
row = table->row_cnt - 1;
}
else if(row < 0) {
row = 0;
}
if((int32_t)table->col_act != col || (int32_t)table->row_act != row) {
table->col_act = col;
table->row_act = row;
lv_obj_invalidate(obj);
scroll_to_selected_cell(obj);
res = lv_obj_send_event(obj, LV_EVENT_VALUE_CHANGED, NULL);
if(res != LV_RESULT_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;
lv_layer_t * layer = lv_event_get_layer(e);
lv_area_t clip_area;
if(!_lv_area_intersect(&clip_area, &obj->coords, &layer->clip_area)) return;
const lv_area_t clip_area_ori = layer->clip_area;
layer->clip_area = clip_area;
lv_point_t txt_size;
lv_area_t cell_area;
int32_t border_width = lv_obj_get_style_border_width(obj, LV_PART_MAIN);
int32_t bg_top = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
int32_t bg_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN);
int32_t bg_left = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
int32_t bg_right = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
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;
uint32_t col;
uint32_t row;
uint32_t cell = 0;
cell_area.y2 = obj->coords.y1 + bg_top - 1 - lv_obj_get_scroll_y(obj) + border_width;
cell_area.x1 = 0;
cell_area.x2 = 0;
int32_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;
/*Handle custom drawer*/
for(row = 0; row < table->row_cnt; row++) {
int32_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) break;
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;
}
uint32_t col_merge = 0;
for(col_merge = 0; col_merge + col < table->col_cnt - 1; col_merge++) {
char * next_cell_data = table->cell_data[cell + col_merge];
if(is_cell_empty(next_cell_data)) break;
lv_table_cell_ctrl_t merge_ctrl = (lv_table_cell_ctrl_t) next_cell_data[0];
if(merge_ctrl & LV_TABLE_CELL_CTRL_MERGE_RIGHT) {
int32_t offset = table->col_w[col + col_merge + 1];
if(rtl) cell_area.x1 -= offset;
else cell_area.x2 += offset;
}
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;
}
rect_dsc_act.base.id1 = row;
rect_dsc_act.base.id2 = col;
label_dsc_act.base.id1 = row;
label_dsc_act.base.id2 = col;
lv_draw_rect(layer, &rect_dsc_act, &cell_area_border);
if(table->cell_data[cell]) {
const int32_t cell_left = lv_obj_get_style_pad_left(obj, LV_PART_ITEMS);
const int32_t cell_right = lv_obj_get_style_pad_right(obj, LV_PART_ITEMS);
const int32_t cell_top = lv_obj_get_style_pad_top(obj, LV_PART_ITEMS);
const int32_t cell_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_ITEMS);
lv_text_flag_t txt_flags = LV_TEXT_FLAG_NONE;
lv_area_t txt_area;
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;
if(crop) txt_flags = LV_TEXT_FLAG_EXPAND;
lv_text_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_clip_area;
bool label_mask_ok;
label_mask_ok = _lv_area_intersect(&label_clip_area, &clip_area, &cell_area);
if(label_mask_ok) {
layer->clip_area = label_clip_area;
label_dsc_act.text = table->cell_data[cell] + 1;
lv_draw_label(layer, &label_dsc_act, &txt_area);
layer->clip_area = clip_area;
}
}
cell += col_merge + 1;
col += col_merge;
}
}
layer->clip_area = clip_area_ori;
}
/* Refreshes size of the table starting from @start_row row */
static void refr_size_form_row(lv_obj_t * obj, uint32_t start_row)
{
const int32_t cell_pad_left = lv_obj_get_style_pad_left(obj, LV_PART_ITEMS);
const int32_t cell_pad_right = lv_obj_get_style_pad_right(obj, LV_PART_ITEMS);
const int32_t cell_pad_top = lv_obj_get_style_pad_top(obj, LV_PART_ITEMS);
const int32_t cell_pad_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_ITEMS);
int32_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_ITEMS);
int32_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);
const int32_t minh = lv_obj_get_style_min_height(obj, LV_PART_ITEMS);
const int32_t maxh = lv_obj_get_style_max_height(obj, LV_PART_ITEMS);
lv_table_t * table = (lv_table_t *)obj;
uint32_t i;
for(i = start_row; i < table->row_cnt; i++) {
int32_t calculated_height = get_row_height(obj, i, font, letter_space, line_space,
cell_pad_left, cell_pad_right, cell_pad_top, cell_pad_bottom);
table->row_h[i] = LV_CLAMP(minh, calculated_height, maxh);
}
lv_obj_refresh_self_size(obj);
lv_obj_invalidate(obj);
}
static void refr_cell_size(lv_obj_t * obj, uint32_t row, uint32_t col)
{
const int32_t cell_pad_left = lv_obj_get_style_pad_left(obj, LV_PART_ITEMS);
const int32_t cell_pad_right = lv_obj_get_style_pad_right(obj, LV_PART_ITEMS);
const int32_t cell_pad_top = lv_obj_get_style_pad_top(obj, LV_PART_ITEMS);
const int32_t cell_pad_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_ITEMS);
int32_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_ITEMS);
int32_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);
const int32_t minh = lv_obj_get_style_min_height(obj, LV_PART_ITEMS);
const int32_t maxh = lv_obj_get_style_max_height(obj, LV_PART_ITEMS);
lv_table_t * table = (lv_table_t *)obj;
int32_t calculated_height = get_row_height(obj, row, font, letter_space, line_space,
cell_pad_left, cell_pad_right, cell_pad_top, cell_pad_bottom);
int32_t prev_row_size = table->row_h[row];
table->row_h[row] = LV_CLAMP(minh, calculated_height, maxh);
/*If the row height haven't changed invalidate only this cell*/
if(prev_row_size == table->row_h[row]) {
lv_area_t cell_area;
get_cell_area(obj, row, col, &cell_area);
lv_area_move(&cell_area, obj->coords.x1, obj->coords.y1);
lv_obj_invalidate_area(obj, &cell_area);
}
else {
lv_obj_refresh_self_size(obj);
lv_obj_invalidate(obj);
}
}
static int32_t get_row_height(lv_obj_t * obj, uint32_t row_id, const lv_font_t * font,
int32_t letter_space, int32_t line_space,
int32_t cell_left, int32_t cell_right, int32_t cell_top, int32_t cell_bottom)
{
lv_table_t * table = (lv_table_t *)obj;
int32_t h_max = lv_font_get_line_height(font) + cell_top + cell_bottom;
/* Calculate the cell_data index where to start */
uint32_t row_start = row_id * table->col_cnt;
/* Traverse the cells in the row_id row */
uint32_t cell;
uint32_t col;
for(cell = row_start, col = 0; cell < row_start + table->col_cnt; cell++, col++) {
char * cell_data = table->cell_data[cell];
if(is_cell_empty(cell_data)) {
continue;
}
int32_t txt_w = table->col_w[col];
/* Traverse the current row from the first until the penultimate column.
* Increment the text width if the cell has the LV_TABLE_CELL_CTRL_MERGE_RIGHT control,
* exit the traversal when the current cell control is not LV_TABLE_CELL_CTRL_MERGE_RIGHT */
uint32_t col_merge = 0;
for(col_merge = 0; col_merge + col < table->col_cnt - 1; col_merge++) {
char * next_cell_data = table->cell_data[cell + col_merge];
if(is_cell_empty(next_cell_data)) break;
lv_table_cell_ctrl_t ctrl = (lv_table_cell_ctrl_t) next_cell_data[0];
if(ctrl & LV_TABLE_CELL_CTRL_MERGE_RIGHT) {
txt_w += table->col_w[col + col_merge + 1];
}
else {
break;
}
}
lv_table_cell_ctrl_t ctrl = (lv_table_cell_ctrl_t) cell_data[0];
/*When cropping the text we can assume the row height is equal to the line height*/
if(ctrl & LV_TABLE_CELL_CTRL_TEXT_CROP) {
h_max = LV_MAX(lv_font_get_line_height(font) + cell_top + cell_bottom,
h_max);
}
/*Else we have to calculate the height of the cell text*/
else {
lv_point_t txt_size;
txt_w -= cell_left + cell_right;
lv_text_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);
/*Skip until one element after the last merged column*/
cell += col_merge;
col += col_merge;
}
}
return h_max;
}
static lv_result_t get_pressed_cell(lv_obj_t * obj, uint32_t * row, uint32_t * col)
{
lv_table_t * table = (lv_table_t *)obj;
lv_indev_type_t type = lv_indev_get_type(lv_indev_active());
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_RESULT_INVALID;
}
lv_point_t p;
lv_indev_get_point(lv_indev_active(), &p);
int32_t tmp;
if(col) {
int32_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) {
int32_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_RESULT_OK;
}
/* Returns number of bytes to allocate based on chars configuration */
static size_t get_cell_txt_len(const char * txt)
{
size_t retval = 0;
#if LV_USE_ARABIC_PERSIAN_CHARS
retval = _lv_text_ap_calc_bytes_cnt(txt) + 1;
#else
/* cell_data layout: [ctrl][txt][trailing '\0' terminator]
* +2 because of the trailing '\0' and the ctrl */
retval = lv_strlen(txt) + 2;
#endif
return retval;
}
/* Copy txt into dst skipping the format byte */
static void copy_cell_txt(char * dst, const char * txt)
{
#if LV_USE_ARABIC_PERSIAN_CHARS
_lv_text_ap_proc(txt, &dst[1]);
#else
lv_strcpy(&dst[1], txt);
#endif
}
static void get_cell_area(lv_obj_t * obj, uint32_t row, uint32_t col, lv_area_t * area)
{
lv_table_t * table = (lv_table_t *)obj;
uint32_t c;
area->x1 = 0;
for(c = 0; c < col; c++) {
area->x1 += table->col_w[c];
}
bool rtl = lv_obj_get_style_base_dir(obj, LV_PART_MAIN) == LV_BASE_DIR_RTL;
if(rtl) {
area->x1 += lv_obj_get_scroll_x(obj);
int32_t w = lv_obj_get_width(obj);
area->x2 = w - area->x1 - lv_obj_get_style_pad_right(obj, 0);
area->x1 = area->x2 - table->col_w[col];
}
else {
area->x1 -= lv_obj_get_scroll_x(obj);
area->x1 += lv_obj_get_style_pad_left(obj, 0);
area->x2 = area->x1 + table->col_w[col] - 1;
}
uint32_t r;
area->y1 = 0;
for(r = 0; r < row; r++) {
area->y1 += table->row_h[r];
}
area->y1 += lv_obj_get_style_pad_top(obj, 0);
area->y1 -= lv_obj_get_scroll_y(obj);
area->y2 = area->y1 + table->row_h[row] - 1;
}
static void scroll_to_selected_cell(lv_obj_t * obj)
{
lv_table_t * table = (lv_table_t *)obj;
lv_area_t a;
get_cell_area(obj, table->row_act, table->col_act, &a);
if(a.x1 < 0) {
lv_obj_scroll_by_bounded(obj, -a.x1, 0, LV_ANIM_ON);
}
else if(a.x2 > lv_obj_get_width(obj)) {
lv_obj_scroll_by_bounded(obj, lv_obj_get_width(obj) - a.x2, 0, LV_ANIM_ON);
}
if(a.y1 < 0) {
lv_obj_scroll_by_bounded(obj, 0, -a.y1, LV_ANIM_ON);
}
else if(a.y2 > lv_obj_get_height(obj)) {
lv_obj_scroll_by_bounded(obj, 0, lv_obj_get_height(obj) - a.y2, LV_ANIM_ON);
}
}
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/table/lv_table.h | /**
* @file lv_table.h
*
*/
#ifndef LV_TABLE_H
#define LV_TABLE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../label/lv_label.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
/*********************
* DEFINES
*********************/
#define LV_TABLE_CELL_NONE 0XFFFF
LV_EXPORT_CONST_INT(LV_TABLE_CELL_NONE);
/**********************
* TYPEDEFS
**********************/
enum _lv_table_cell_ctrl_t {
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,
};
#ifdef DOXYGEN
typedef _lv_table_cell_ctrl_t lv_table_cell_ctrl_t;
#else
typedef uint32_t lv_table_cell_ctrl_t;
#endif /*DOXYGEN*/
/*Data of table*/
typedef struct {
lv_obj_t obj;
uint32_t col_cnt;
uint32_t row_cnt;
char ** cell_data;
int32_t * row_h;
int32_t * col_w;
uint32_t col_act;
uint32_t row_act;
} lv_table_t;
extern const lv_obj_class_t lv_table_class;
/**********************
* 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, uint32_t row, uint32_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, uint32_t row, uint32_t col, const char * fmt,
...) LV_FORMAT_ATTRIBUTE(4, 5);
/**
* 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, uint32_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, uint32_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, uint32_t col_id, int32_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, uint32_t row, uint32_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, uint32_t row, uint32_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, uint32_t row, uint32_t col);
/**
* Get the number of rows.
* @param obj table pointer to a Table object
* @return number of rows.
*/
uint32_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.
*/
uint32_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
*/
int32_t lv_table_get_col_width(lv_obj_t * obj, uint32_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, uint32_t row, uint32_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, uint32_t * row, uint32_t * col);
/**********************
* MACROS
**********************/
#endif /*LV_USE_TABLE*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_TABLE_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/scale/lv_scale.h | /**
* @file lv_scale.h
*
*/
#ifndef LV_SCALE_H
#define LV_SCALE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../lv_conf_internal.h"
#if LV_USE_SCALE != 0
#include "../../core/lv_obj.h"
/*********************
* DEFINES
*********************/
/**Default value of total minor ticks. */
#define LV_SCALE_TOTAL_TICK_COUNT_DEFAULT (11U)
LV_EXPORT_CONST_INT(LV_SCALE_TOTAL_TICK_COUNT_DEFAULT);
/**Default value of major tick every nth ticks. */
#define LV_SCALE_MAJOR_TICK_EVERY_DEFAULT (5U)
LV_EXPORT_CONST_INT(LV_SCALE_MAJOR_TICK_EVERY_DEFAULT);
/**Default value of scale label enabled. */
#define LV_SCALE_LABEL_ENABLED_DEFAULT (1U)
LV_EXPORT_CONST_INT(LV_SCALE_LABEL_ENABLED_DEFAULT);
/**********************
* TYPEDEFS
**********************/
/**
* Scale mode
*/
enum {
LV_SCALE_MODE_HORIZONTAL_TOP = 0x00U,
LV_SCALE_MODE_HORIZONTAL_BOTTOM = 0x01U,
LV_SCALE_MODE_VERTICAL_LEFT = 0x02U,
LV_SCALE_MODE_VERTICAL_RIGHT = 0x04U,
LV_SCALE_MODE_ROUND_INNER = 0x08U,
LV_SCALE_MODE_ROUND_OUTER = 0x10U,
_LV_SCALE_MODE_LAST
};
typedef uint32_t lv_scale_mode_t;
typedef struct {
lv_style_t * main_style;
lv_style_t * indicator_style;
lv_style_t * items_style;
int32_t minor_range;
int32_t major_range;
uint32_t first_tick_idx_in_section;
uint32_t last_tick_idx_in_section;
uint32_t first_tick_idx_is_major;
uint32_t last_tick_idx_is_major;
int32_t first_tick_in_section_width;
int32_t last_tick_in_section_width;
lv_point_t first_tick_in_section;
lv_point_t last_tick_in_section;
} lv_scale_section_t;
typedef struct {
lv_obj_t obj;
lv_ll_t section_ll; /**< Linked list for the sections (stores lv_scale_section_t)*/
const char ** txt_src;
int32_t custom_label_cnt;
int32_t major_len;
int32_t minor_len;
int32_t range_min;
int32_t range_max;
uint32_t total_tick_count : 15;
uint32_t major_tick_every : 15;
lv_scale_mode_t mode;
uint32_t label_enabled : 1;
uint32_t post_draw : 1;
int32_t last_tick_width;
int32_t first_tick_width;
/* Round scale */
uint32_t angle_range;
int32_t rotation;
} lv_scale_t;
extern const lv_obj_class_t lv_scale_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create an scale object
* @param parent pointer to an object, it will be the parent of the new scale
* @return pointer to the created scale
*/
lv_obj_t * lv_scale_create(lv_obj_t * parent);
/*======================
* Add/remove functions
*=====================*/
/*=====================
* Setter functions
*====================*/
/**
* Set scale mode. See @ref lv_scale_mode_t
* @param obj pointer the scale object
* @param mode New scale mode
*/
void lv_scale_set_mode(lv_obj_t * obj, lv_scale_mode_t mode);
/**
* Set scale total tick count (including minor and major ticks)
* @param obj pointer the scale object
* @param total_tick_count New total tick count
*/
void lv_scale_set_total_tick_count(lv_obj_t * obj, int32_t total_tick_count);
/**
* Sets how often the major tick will be drawn
* @param obj pointer the scale object
* @param major_tick_every New count for major tick drawing
*/
void lv_scale_set_major_tick_every(lv_obj_t * obj, int32_t major_tick_every);
/**
* Sets label visibility
* @param obj pointer the scale object
* @param show_label Show axis label
*/
void lv_scale_set_label_show(lv_obj_t * obj, bool show_label);
/**
* Sets major tick length
* @param obj pointer the scale object
* @param major_len Major tick length
*/
void lv_scale_set_major_tick_length(lv_obj_t * obj, int32_t major_len);
/**
* Sets major tick length
* @param obj pointer the scale object
* @param minor_len Minor tick length
*/
void lv_scale_set_minor_tick_length(lv_obj_t * obj, int32_t minor_len);
/**
* Set the minimal and maximal values on a scale
* @param obj pointer to a scale object
* @param min minimum value of the scale
* @param max maximum value of the scale
*/
void lv_scale_set_range(lv_obj_t * obj, int32_t min, int32_t max);
/**
* Set properties specific to round scale
* @param obj pointer to a scale object
* @param angle_range the angular range of the scale
* @param rotation the angular offset from the 3 o'clock position (clock-wise)
*/
void lv_scale_set_round_props(lv_obj_t * obj, uint32_t angle_range, int32_t rotation);
/**
* Set custom text source for major ticks labels
* @param obj pointer to a scale object
* @param txt_src pointer to an array of strings which will be display at major ticks
*/
void lv_scale_set_text_src(lv_obj_t * obj, const char * txt_src[]);
/**
* Draw the scale after all the children are drawn
* @param obj pointer to a scale object
* @param en true: enable post draw
*/
void lv_scale_set_post_draw(lv_obj_t * obj, bool en);
/**
* Add a section to the given scale
* @param obj pointer to a scale object
* @return pointer to the new section
*/
lv_scale_section_t * lv_scale_add_section(lv_obj_t * obj);
/**
* Set the range for the given scale section
* @param obj pointer to a scale section object
* @param minor_range section new minor range
* @param major_range section new major range
*/
void lv_scale_section_set_range(lv_scale_section_t * section, int32_t minor_range, int32_t major_range);
/**
* Set the style of the part for the given scale section
* @param obj pointer to a scale section object
* @param part Section part
* @param section_part_style Pointer to the section part style
*/
void lv_scale_section_set_style(lv_scale_section_t * section, uint32_t part, lv_style_t * section_part_style);
/*=====================
* Getter functions
*====================*/
/**********************
* MACROS
**********************/
#endif /*LV_USE_SCALE*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_SCALE_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/scale/lv_scale.c | /**
* @file lv_scale.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_scale.h"
#if LV_USE_SCALE != 0
#include "../../core/lv_group.h"
#include "../../misc/lv_assert.h"
#include "../../misc/lv_math.h"
#include "../../draw/lv_draw_arc.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_scale_class
#define LV_SCALE_LABEL_TXT_LEN (20U)
#define LV_SCALE_DEFAULT_ANGLE_RANGE ((uint32_t) 270U)
#define LV_SCALE_DEFAULT_ROTATION ((int32_t) 135U)
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_scale_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_scale_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_scale_event(const lv_obj_class_t * class_p, lv_event_t * event);
static void scale_draw_main(lv_obj_t * obj, lv_event_t * event);
static void scale_draw_indicator(lv_obj_t * obj, lv_event_t * event);
static void scale_get_center(const lv_obj_t * obj, lv_point_t * center, int32_t * arc_r);
static void scale_get_tick_points(lv_obj_t * obj, const uint32_t tick_idx, bool is_major_tick,
lv_point_t * tick_point_a, lv_point_t * tick_point_b);
static void scale_get_label_coords(lv_obj_t * obj, lv_draw_label_dsc_t * label_dsc, lv_point_t * tick_point,
lv_area_t * label_coords);
static void scale_set_indicator_label_properties(lv_obj_t * obj, lv_draw_label_dsc_t * label_dsc,
lv_style_t * indicator_section_style);
static void scale_set_line_properties(lv_obj_t * obj, lv_draw_line_dsc_t * line_dsc, lv_style_t * section_style,
uint32_t part);
static void scale_set_arc_properties(lv_obj_t * obj, lv_draw_arc_dsc_t * arc_dsc, lv_style_t * section_style);
/* Helpers */
static void scale_find_section_tick_idx(lv_obj_t * obj);
static void scale_store_main_line_tick_width_compensation(lv_obj_t * obj, const uint32_t tick_idx,
const bool is_major_tick, const int32_t major_tick_width, const int32_t minor_tick_width);
static void scale_store_section_line_tick_width_compensation(lv_obj_t * obj, const bool is_major_tick,
lv_draw_label_dsc_t * label_dsc, lv_draw_line_dsc_t * major_tick_dsc, lv_draw_line_dsc_t * minor_tick_dsc,
const int32_t tick_value, const uint8_t tick_idx, lv_point_t * tick_point_a);
static void scale_build_custom_label_text(lv_obj_t * obj, lv_draw_label_dsc_t * label_dsc,
const uint16_t major_tick_idx);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_scale_class = {
.constructor_cb = lv_scale_constructor,
.destructor_cb = lv_scale_destructor,
.event_cb = lv_scale_event,
.instance_size = sizeof(lv_scale_t),
.editable = LV_OBJ_CLASS_EDITABLE_TRUE,
.base_class = &lv_obj_class,
.name = "scale",
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_scale_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_scale_set_mode(lv_obj_t * obj, lv_scale_mode_t mode)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_scale_t * scale = (lv_scale_t *)obj;
scale->mode = mode;
lv_obj_invalidate(obj);
}
void lv_scale_set_total_tick_count(lv_obj_t * obj, int32_t total_tick_count)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_scale_t * scale = (lv_scale_t *)obj;
scale->total_tick_count = total_tick_count;
lv_obj_invalidate(obj);
}
void lv_scale_set_major_tick_every(lv_obj_t * obj, int32_t major_tick_every)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_scale_t * scale = (lv_scale_t *)obj;
scale->major_tick_every = major_tick_every;
lv_obj_invalidate(obj);
}
void lv_scale_set_major_tick_length(lv_obj_t * obj, int32_t major_len)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_scale_t * scale = (lv_scale_t *)obj;
scale->major_len = major_len;
lv_obj_invalidate(obj);
}
void lv_scale_set_minor_tick_length(lv_obj_t * obj, int32_t minor_len)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_scale_t * scale = (lv_scale_t *)obj;
scale->minor_len = minor_len;
lv_obj_invalidate(obj);
}
void lv_scale_set_label_show(lv_obj_t * obj, bool show_label)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_scale_t * scale = (lv_scale_t *)obj;
scale->label_enabled = show_label;
lv_obj_invalidate(obj);
}
void lv_scale_set_range(lv_obj_t * obj, int32_t min, int32_t max)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_scale_t * scale = (lv_scale_t *)obj;
scale->range_min = min;
scale->range_max = max;
lv_obj_invalidate(obj);
}
void lv_scale_set_round_props(lv_obj_t * obj, uint32_t angle_range, int32_t rotation)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_scale_t * scale = (lv_scale_t *)obj;
scale->angle_range = angle_range;
scale->rotation = rotation;
lv_obj_invalidate(obj);
}
void lv_scale_set_text_src(lv_obj_t * obj, const char * txt_src[])
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_scale_t * scale = (lv_scale_t *)obj;
scale->txt_src = txt_src;
scale->custom_label_cnt = 0;
if(scale->txt_src) {
int32_t idx;
for(idx = 0; txt_src[idx]; ++idx) {
scale->custom_label_cnt++;
}
}
lv_obj_invalidate(obj);
}
void lv_scale_set_post_draw(lv_obj_t * obj, bool en)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_scale_t * scale = (lv_scale_t *)obj;
scale->post_draw = en;
lv_obj_invalidate(obj);
}
lv_scale_section_t * lv_scale_add_section(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_scale_t * scale = (lv_scale_t *)obj;
lv_scale_section_t * section = _lv_ll_ins_head(&scale->section_ll);
LV_ASSERT_MALLOC(section);
if(section == NULL) return NULL;
/* Section default values */
section->main_style = NULL;
section->indicator_style = NULL;
section->items_style = NULL;
section->minor_range = 0U;
section->major_range = 0U;
section->first_tick_idx_in_section = 255U;
section->last_tick_idx_in_section = 255U;
section->first_tick_idx_is_major = 0U;
section->last_tick_idx_is_major = 0U;
section->first_tick_in_section_width = 0U;
section->last_tick_in_section_width = 0U;
return section;
}
void lv_scale_section_set_range(lv_scale_section_t * section, int32_t minor_range, int32_t major_range)
{
if(NULL == section) return;
section->minor_range = minor_range;
section->major_range = major_range;
}
void lv_scale_section_set_style(lv_scale_section_t * section, uint32_t part, lv_style_t * section_part_style)
{
if(NULL == section) return;
switch(part) {
case LV_PART_MAIN:
section->main_style = section_part_style;
break;
case LV_PART_INDICATOR:
section->indicator_style = section_part_style;
break;
case LV_PART_ITEMS:
section->items_style = section_part_style;
break;
default:
/* Invalid part */
break;
}
}
/*=====================
* Getter functions
*====================*/
/*=====================
* Other functions
*====================*/
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_scale_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_scale_t * scale = (lv_scale_t *)obj;
_lv_ll_init(&scale->section_ll, sizeof(lv_scale_section_t));
scale->total_tick_count = LV_SCALE_TOTAL_TICK_COUNT_DEFAULT;
scale->major_tick_every = LV_SCALE_MAJOR_TICK_EVERY_DEFAULT;
scale->mode = LV_SCALE_MODE_HORIZONTAL_BOTTOM;
scale->label_enabled = LV_SCALE_LABEL_ENABLED_DEFAULT;
scale->angle_range = LV_SCALE_DEFAULT_ANGLE_RANGE;
scale->rotation = LV_SCALE_DEFAULT_ROTATION;
scale->range_min = 0U;
scale->range_max = 100U;
scale->major_len = 10U;
scale->minor_len = 5u;
scale->last_tick_width = 0U;
scale->first_tick_width = 0U;
scale->post_draw = false;
scale->custom_label_cnt = 0U;
scale->txt_src = NULL;
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_scale_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_scale_t * scale = (lv_scale_t *)obj;
lv_scale_section_t * section;
while(scale->section_ll.head) {
section = _lv_ll_get_head(&scale->section_ll);
_lv_ll_remove(&scale->section_ll, section);
lv_free(section);
}
_lv_ll_clear(&scale->section_ll);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_scale_event(const lv_obj_class_t * class_p, lv_event_t * event)
{
LV_UNUSED(class_p);
/*Call the ancestor's event handler*/
lv_result_t res = lv_obj_event_base(MY_CLASS, event);
if(res != LV_RESULT_OK) return;
lv_event_code_t event_code = lv_event_get_code(event);
lv_obj_t * obj = lv_event_get_target(event);
lv_scale_t * scale = (lv_scale_t *) obj;
LV_UNUSED(scale);
if(event_code == LV_EVENT_DRAW_MAIN) {
if(scale->post_draw == false) {
scale_find_section_tick_idx(obj);
scale_draw_indicator(obj, event);
scale_draw_main(obj, event);
}
}
if(event_code == LV_EVENT_DRAW_POST) {
if(scale->post_draw == true) {
scale_find_section_tick_idx(obj);
scale_draw_indicator(obj, event);
scale_draw_main(obj, event);
}
}
else if(event_code == LV_EVENT_REFR_EXT_DRAW_SIZE) {
/* NOTE: Extend scale draw size so the first tick label can be shown */
lv_event_set_ext_draw_size(event, 100);
}
else {
/* Nothing to do. Invalid event */
}
}
static void scale_draw_indicator(lv_obj_t * obj, lv_event_t * event)
{
lv_scale_t * scale = (lv_scale_t *)obj;
lv_layer_t * layer = lv_event_get_layer(event);
if(scale->total_tick_count <= 1) return;
lv_draw_label_dsc_t label_dsc;
lv_draw_label_dsc_init(&label_dsc);
/* Formatting the labels with the configured style for LV_PART_INDICATOR */
lv_obj_init_draw_label_dsc(obj, LV_PART_INDICATOR, &label_dsc);
/* Major tick style */
lv_draw_line_dsc_t major_tick_dsc;
lv_draw_line_dsc_init(&major_tick_dsc);
lv_obj_init_draw_line_dsc(obj, LV_PART_INDICATOR, &major_tick_dsc);
/* Configure line draw descriptor for the minor tick drawing */
lv_draw_line_dsc_t minor_tick_dsc;
lv_draw_line_dsc_init(&minor_tick_dsc);
lv_obj_init_draw_line_dsc(obj, LV_PART_ITEMS, &minor_tick_dsc);
/* Main line style */
lv_draw_line_dsc_t main_line_dsc;
lv_draw_line_dsc_init(&main_line_dsc);
lv_obj_init_draw_line_dsc(obj, LV_PART_MAIN, &main_line_dsc);
if((LV_SCALE_MODE_VERTICAL_LEFT == scale->mode || LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode)
|| (LV_SCALE_MODE_HORIZONTAL_BOTTOM == scale->mode || LV_SCALE_MODE_HORIZONTAL_TOP == scale->mode)) {
uint32_t total_tick_count = scale->total_tick_count;
uint32_t tick_idx = 0;
uint32_t major_tick_idx = 0;
for(tick_idx = 0; tick_idx < total_tick_count; tick_idx++) {
/* A major tick is the one which has a label in it */
bool is_major_tick = false;
if(tick_idx % scale->major_tick_every == 0) is_major_tick = true;
if(is_major_tick) major_tick_idx++;
const int32_t tick_value = lv_map(tick_idx, 0U, total_tick_count - 1, scale->range_min, scale->range_max);
/* Overwrite label and tick properties if tick value is within section range */
lv_scale_section_t * section;
_LV_LL_READ_BACK(&scale->section_ll, section) {
if(section->minor_range <= tick_value && section->major_range >= tick_value) {
if(is_major_tick) {
scale_set_indicator_label_properties(obj, &label_dsc, section->indicator_style);
scale_set_line_properties(obj, &major_tick_dsc, section->indicator_style, LV_PART_INDICATOR);
}
else {
scale_set_line_properties(obj, &minor_tick_dsc, section->items_style, LV_PART_ITEMS);
}
break;
}
else {
/* Tick is not in section, get the proper styles */
lv_obj_init_draw_label_dsc(obj, LV_PART_INDICATOR, &label_dsc);
lv_obj_init_draw_line_dsc(obj, LV_PART_INDICATOR, &major_tick_dsc);
lv_obj_init_draw_line_dsc(obj, LV_PART_ITEMS, &minor_tick_dsc);
}
}
/* The tick is represented by a line. We need two points to draw it */
lv_point_t tick_point_a;
lv_point_t tick_point_b;
scale_get_tick_points(obj, tick_idx, is_major_tick, &tick_point_a, &tick_point_b);
/* Setup a label if they're enabled and we're drawing a major tick */
if(scale->label_enabled && is_major_tick) {
/* Label text setup */
char text_buffer[LV_SCALE_LABEL_TXT_LEN] = {0};
lv_area_t label_coords;
/* Check if the custom text array has element for this major tick index */
if(scale->txt_src) {
scale_build_custom_label_text(obj, &label_dsc, major_tick_idx);
}
else { /* Add label with mapped values */
lv_snprintf(text_buffer, sizeof(text_buffer), "%" LV_PRId32, tick_value);
label_dsc.text = text_buffer;
label_dsc.text_local = 1;
}
scale_get_label_coords(obj, &label_dsc, &tick_point_b, &label_coords);
lv_draw_label(layer, &label_dsc, &label_coords);
}
/* Store initial and last tick widths to be used in the main line drawing */
scale_store_main_line_tick_width_compensation(obj, tick_idx, is_major_tick, major_tick_dsc.width, minor_tick_dsc.width);
/* Store the first and last section tick vertical/horizontal position */
scale_store_section_line_tick_width_compensation(obj, is_major_tick, &label_dsc, &major_tick_dsc, &minor_tick_dsc,
tick_value, tick_idx, &tick_point_a);
if(is_major_tick) {
major_tick_dsc.p1_x = tick_point_a.x;
major_tick_dsc.p1_y = tick_point_a.y;
major_tick_dsc.p2_x = tick_point_b.x;
major_tick_dsc.p2_y = tick_point_b.y;
lv_draw_line(layer, &major_tick_dsc);
}
else {
minor_tick_dsc.p1_x = tick_point_a.x;
minor_tick_dsc.p1_y = tick_point_a.y;
minor_tick_dsc.p2_x = tick_point_b.x;
minor_tick_dsc.p2_y = tick_point_b.y;
lv_draw_line(layer, &minor_tick_dsc);
}
}
}
else if(LV_SCALE_MODE_ROUND_OUTER == scale->mode || LV_SCALE_MODE_ROUND_INNER == scale->mode) {
lv_area_t scale_area;
lv_obj_get_content_coords(obj, &scale_area);
/* Find the center of the scale */
lv_point_t center_point;
int32_t radius_edge = LV_MIN(lv_area_get_width(&scale_area) / 2U, lv_area_get_height(&scale_area) / 2U);
center_point.x = scale_area.x1 + radius_edge;
center_point.y = scale_area.y1 + radius_edge;
/* Major tick */
major_tick_dsc.raw_end = 0;
uint32_t label_gap = 15U; /* TODO: Add to style properties */
uint32_t tick_idx = 0;
uint32_t major_tick_idx = 0;
for(tick_idx = 0; tick_idx < scale->total_tick_count; tick_idx++) {
/* A major tick is the one which has a label in it */
bool is_major_tick = false;
if(tick_idx % scale->major_tick_every == 0) is_major_tick = true;
if(is_major_tick) major_tick_idx++;
const int32_t tick_value = lv_map(tick_idx, 0U, scale->total_tick_count - 1, scale->range_min, scale->range_max);
/* Overwrite label and tick properties if tick value is within section range */
lv_scale_section_t * section;
_LV_LL_READ_BACK(&scale->section_ll, section) {
if(section->minor_range <= tick_value && section->major_range >= tick_value) {
if(is_major_tick) {
scale_set_indicator_label_properties(obj, &label_dsc, section->indicator_style);
scale_set_line_properties(obj, &major_tick_dsc, section->indicator_style, LV_PART_INDICATOR);
}
else {
scale_set_line_properties(obj, &minor_tick_dsc, section->items_style, LV_PART_ITEMS);
}
break;
}
else {
/* Tick is not in section, get the proper styles */
lv_obj_init_draw_label_dsc(obj, LV_PART_INDICATOR, &label_dsc);
lv_obj_init_draw_line_dsc(obj, LV_PART_INDICATOR, &major_tick_dsc);
lv_obj_init_draw_line_dsc(obj, LV_PART_ITEMS, &minor_tick_dsc);
}
}
/* The tick is represented by a line. We need two points to draw it */
lv_point_t tick_point_a;
lv_point_t tick_point_b;
scale_get_tick_points(obj, tick_idx, is_major_tick, &tick_point_a, &tick_point_b);
/* Setup a label if they're enabled and we're drawing a major tick */
if(scale->label_enabled && is_major_tick) {
/* Label text setup */
char text_buffer[LV_SCALE_LABEL_TXT_LEN] = {0};
lv_area_t label_coords;
/* Check if the custom text array has element for this major tick index */
if(scale->txt_src) {
scale_build_custom_label_text(obj, &label_dsc, major_tick_idx);
}
else { /* Add label with mapped values */
lv_snprintf(text_buffer, sizeof(text_buffer), "%" LV_PRId32, tick_value);
label_dsc.text = text_buffer;
label_dsc.text_local = 1;
}
/* Also take into consideration the letter space of the style */
int32_t angle_upscale = ((tick_idx * scale->angle_range) * 10U) / (scale->total_tick_count - 1);
angle_upscale += scale->rotation * 10U;
uint32_t radius_text = 0;
if(LV_SCALE_MODE_ROUND_INNER == scale->mode) {
radius_text = (radius_edge - scale->major_len) - (label_gap + label_dsc.letter_space);
}
else if(LV_SCALE_MODE_ROUND_OUTER == scale->mode) {
radius_text = (radius_edge + scale->major_len) + (label_gap + label_dsc.letter_space);
}
else { /* Nothing to do */ }
lv_point_t point;
point.x = center_point.x + radius_text;
point.y = center_point.y;
lv_point_transform(&point, angle_upscale, LV_SCALE_NONE, LV_SCALE_NONE, ¢er_point, false);
scale_get_label_coords(obj, &label_dsc, &point, &label_coords);
lv_draw_label(layer, &label_dsc, &label_coords);
}
/* Store initial and last tick widths to be used in the main line drawing */
scale_store_main_line_tick_width_compensation(obj, tick_idx, is_major_tick, major_tick_dsc.width, minor_tick_dsc.width);
if(is_major_tick) {
major_tick_dsc.p1_x = tick_point_a.x;
major_tick_dsc.p1_y = tick_point_a.y;
major_tick_dsc.p2_x = tick_point_b.x;
major_tick_dsc.p2_y = tick_point_b.y;
lv_draw_line(layer, &major_tick_dsc);
}
else {
minor_tick_dsc.p1_x = tick_point_a.x;
minor_tick_dsc.p1_y = tick_point_a.y;
minor_tick_dsc.p2_x = tick_point_b.x;
minor_tick_dsc.p2_y = tick_point_b.y;
lv_draw_line(layer, &minor_tick_dsc);
}
}
}
else { /* Nothing to do */ }
}
static void scale_draw_main(lv_obj_t * obj, lv_event_t * event)
{
lv_scale_t * scale = (lv_scale_t *)obj;
lv_layer_t * layer = lv_event_get_layer(event);
if(scale->total_tick_count <= 1) return;
if((LV_SCALE_MODE_VERTICAL_LEFT == scale->mode || LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode)
|| (LV_SCALE_MODE_HORIZONTAL_BOTTOM == scale->mode || LV_SCALE_MODE_HORIZONTAL_TOP == scale->mode)) {
/* Configure both line and label draw descriptors for the tick and label drawings */
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);
/* Get style properties so they can be used in the main line drawing */
const int32_t border_width = lv_obj_get_style_border_width(obj, LV_PART_MAIN);
const int32_t pad_top = lv_obj_get_style_pad_top(obj, LV_PART_MAIN) + border_width;
const int32_t pad_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN) + border_width;
const int32_t pad_left = lv_obj_get_style_pad_left(obj, LV_PART_MAIN) + border_width;
const int32_t pad_right = lv_obj_get_style_pad_right(obj, LV_PART_MAIN) + border_width;
int32_t x_ofs = 0U;
int32_t y_ofs = 0U;
if(LV_SCALE_MODE_VERTICAL_LEFT == scale->mode) {
x_ofs = obj->coords.x2 + (line_dsc.width / 2U) - pad_right;
y_ofs = obj->coords.y1 + pad_top;
}
else if(LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode) {
x_ofs = obj->coords.x1 + (line_dsc.width / 2U) + pad_left;
y_ofs = obj->coords.y1 + pad_top;
}
if(LV_SCALE_MODE_HORIZONTAL_BOTTOM == scale->mode) {
x_ofs = obj->coords.x1 + pad_right;
y_ofs = obj->coords.y1 + (line_dsc.width / 2U) + pad_top;
}
else if(LV_SCALE_MODE_HORIZONTAL_TOP == scale->mode) {
x_ofs = obj->coords.x1 + pad_left;
y_ofs = obj->coords.y2 + (line_dsc.width / 2U) - pad_bottom;
}
else { /* Nothing to do */ }
lv_point_t main_line_point_a;
lv_point_t main_line_point_b;
/* Setup the tick points */
if(LV_SCALE_MODE_VERTICAL_LEFT == scale->mode || LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode) {
main_line_point_a.x = x_ofs - 1U;
main_line_point_a.y = y_ofs;
main_line_point_b.x = x_ofs - 1U;
main_line_point_b.y = obj->coords.y2 - pad_bottom;
/* Adjust main line with initial and last tick width */
main_line_point_a.y -= scale->last_tick_width / 2U;
main_line_point_b.y += scale->first_tick_width / 2U;
}
else {
main_line_point_a.x = x_ofs;
main_line_point_a.y = y_ofs;
/* X of second point starts at the edge of the object minus the left pad */
main_line_point_b.x = obj->coords.x2 - (pad_left);
main_line_point_b.y = y_ofs;
/* Adjust main line with initial and last tick width */
main_line_point_a.x -= scale->last_tick_width / 2U;
main_line_point_b.x += scale->first_tick_width / 2U;
}
line_dsc.p1_x = main_line_point_a.x;
line_dsc.p1_y = main_line_point_a.y;
line_dsc.p2_x = main_line_point_b.x;
line_dsc.p2_y = main_line_point_b.y;
lv_draw_line(layer, &line_dsc);
lv_scale_section_t * section;
_LV_LL_READ_BACK(&scale->section_ll, section) {
lv_draw_line_dsc_t main_line_section_dsc;
lv_draw_line_dsc_init(&main_line_section_dsc);
lv_obj_init_draw_line_dsc(obj, LV_PART_MAIN, &main_line_section_dsc);
/* Calculate the points of the section line */
lv_point_t main_point_a;
lv_point_t main_point_b;
/* Calculate the position of the section based on the ticks (first and last) index */
if(LV_SCALE_MODE_VERTICAL_LEFT == scale->mode || LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode) {
/* Calculate position of the first tick in the section */
main_point_a.x = main_line_point_a.x;
int32_t tmp = (int32_t)(section->first_tick_in_section_width / 2U);
main_point_a.y = section->first_tick_in_section.y + tmp;
/* Calculate position of the last tick in the section */
main_point_b.x = main_line_point_a.x;
tmp = (int32_t)(section->last_tick_in_section_width / 2U);
main_point_b.y = section->last_tick_in_section.y - tmp;
}
else {
/* Calculate position of the first tick in the section */
int32_t tmp = (int32_t)(section->first_tick_in_section_width / 2U);
main_point_a.x = section->first_tick_in_section.x - tmp;
main_point_a.y = main_line_point_a.y;
/* Calculate position of the last tick in the section */
tmp = (int32_t)(section->last_tick_in_section_width / 2U);
main_point_b.x = section->last_tick_in_section.x + tmp;
main_point_b.y = main_line_point_a.y;
}
scale_set_line_properties(obj, &main_line_section_dsc, section->main_style, LV_PART_MAIN);
main_line_section_dsc.p1_x = main_point_a.x;
main_line_section_dsc.p1_y = main_point_a.y;
main_line_section_dsc.p2_x = main_point_b.x;
main_line_section_dsc.p2_y = main_point_b.y;
lv_draw_line(layer, &main_line_section_dsc);
}
}
else if(LV_SCALE_MODE_ROUND_OUTER == scale->mode || LV_SCALE_MODE_ROUND_INNER == scale->mode) {
/* Configure arc draw descriptors for the main part */
lv_draw_arc_dsc_t arc_dsc;
lv_draw_arc_dsc_init(&arc_dsc);
lv_obj_init_draw_arc_dsc(obj, LV_PART_MAIN, &arc_dsc);
lv_point_t arc_center;
int32_t arc_radius;
scale_get_center(obj, &arc_center, &arc_radius);
/* TODO: Add compensation for the width of the first and last tick over the arc */
const int32_t start_angle = lv_map(scale->range_min, scale->range_min, scale->range_max, scale->rotation,
scale->rotation + scale->angle_range);
const int32_t end_angle = lv_map(scale->range_max, scale->range_min, scale->range_max, scale->rotation,
scale->rotation + scale->angle_range);
arc_dsc.center = arc_center;
arc_dsc.radius = arc_radius;
arc_dsc.start_angle = start_angle;
arc_dsc.end_angle = end_angle;
lv_draw_arc(layer, &arc_dsc);
lv_scale_section_t * section;
_LV_LL_READ_BACK(&scale->section_ll, section) {
lv_draw_arc_dsc_t main_arc_section_dsc;
lv_draw_arc_dsc_init(&main_arc_section_dsc);
lv_obj_init_draw_arc_dsc(obj, LV_PART_MAIN, &main_arc_section_dsc);
lv_point_t section_arc_center;
int32_t section_arc_radius;
scale_get_center(obj, §ion_arc_center, §ion_arc_radius);
/* TODO: Add compensation for the width of the first and last tick over the arc */
const int32_t section_start_angle = lv_map(section->minor_range, scale->range_min, scale->range_max, scale->rotation,
scale->rotation + scale->angle_range);
const int32_t section_end_angle = lv_map(section->major_range, scale->range_min, scale->range_max, scale->rotation,
scale->rotation + scale->angle_range);
scale_set_arc_properties(obj, &main_arc_section_dsc, section->main_style);
main_arc_section_dsc.center = section_arc_center;
main_arc_section_dsc.radius = section_arc_radius;
main_arc_section_dsc.start_angle = section_start_angle;
main_arc_section_dsc.end_angle = section_end_angle;
lv_draw_arc(layer, &main_arc_section_dsc);
}
}
else { /* Nothing to do */ }
}
/**
* Get center point and radius of scale arc
* @param obj pointer to a scale object
* @param center pointer to center
* @param arc_r pointer to arc radius
*/
static void scale_get_center(const lv_obj_t * obj, lv_point_t * center, int32_t * arc_r)
{
int32_t left_bg = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
int32_t right_bg = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
int32_t top_bg = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
int32_t bottom_bg = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN);
int32_t r = (LV_MIN(lv_obj_get_width(obj) - left_bg - right_bg, lv_obj_get_height(obj) - top_bg - bottom_bg)) / 2U;
center->x = obj->coords.x1 + r + left_bg;
center->y = obj->coords.y1 + r + top_bg;
if(arc_r) *arc_r = r;
}
/**
* Get points for ticks
*
* In order to draw ticks we need two points, this interface returns both points for all scale modes.
*
* @param obj pointer to a scale object
* @param tick_idx index of the current tick
* @param is_major_tick true if tick_idx is a major tick
* @param tick_point_a pointer to point 'a' of the tick
* @param tick_point_b pointer to point 'b' of the tick
*/
static void scale_get_tick_points(lv_obj_t * obj, const uint32_t tick_idx, bool is_major_tick,
lv_point_t * tick_point_a, lv_point_t * tick_point_b)
{
lv_scale_t * scale = (lv_scale_t *)obj;
/* Main line style */
lv_draw_line_dsc_t main_line_dsc;
lv_draw_line_dsc_init(&main_line_dsc);
lv_obj_init_draw_line_dsc(obj, LV_PART_MAIN, &main_line_dsc);
int32_t minor_len = 0;
int32_t major_len = 0;
if(is_major_tick) {
major_len = scale->major_len;
}
else {
minor_len = scale->minor_len;
}
if((LV_SCALE_MODE_VERTICAL_LEFT == scale->mode || LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode)
|| (LV_SCALE_MODE_HORIZONTAL_BOTTOM == scale->mode || LV_SCALE_MODE_HORIZONTAL_TOP == scale->mode)) {
/* Get style properties so they can be used in the tick and label drawing */
const int32_t border_width = lv_obj_get_style_border_width(obj, LV_PART_MAIN);
const int32_t pad_top = lv_obj_get_style_pad_top(obj, LV_PART_MAIN) + border_width;
const int32_t pad_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN) + border_width;
const int32_t pad_right = lv_obj_get_style_pad_right(obj, LV_PART_MAIN) + border_width;
const int32_t pad_left = lv_obj_get_style_pad_left(obj, LV_PART_MAIN) + border_width;
const int32_t tick_pad_right = lv_obj_get_style_pad_right(obj, LV_PART_ITEMS);
const int32_t tick_pad_left = lv_obj_get_style_pad_left(obj, LV_PART_ITEMS);
const int32_t tick_pad_top = lv_obj_get_style_pad_top(obj, LV_PART_ITEMS);
const int32_t tick_pad_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_ITEMS);
int32_t x_ofs = 0U;
int32_t y_ofs = 0U;
if(LV_SCALE_MODE_VERTICAL_LEFT == scale->mode) {
x_ofs = obj->coords.x2 + (main_line_dsc.width / 2U) - pad_right;
y_ofs = obj->coords.y1 + (pad_top + tick_pad_top);
}
else if(LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode) {
x_ofs = obj->coords.x1 + (main_line_dsc.width / 2U) + pad_left;
y_ofs = obj->coords.y1 + (pad_top + tick_pad_top);
}
else if(LV_SCALE_MODE_HORIZONTAL_BOTTOM == scale->mode) {
x_ofs = obj->coords.x1 + (pad_right + tick_pad_right);
y_ofs = obj->coords.y1 + (main_line_dsc.width / 2U) + pad_top;
}
else if(LV_SCALE_MODE_HORIZONTAL_TOP == scale->mode) {
x_ofs = obj->coords.x1 + (pad_left + tick_pad_left);
y_ofs = obj->coords.y2 + (main_line_dsc.width / 2U) - pad_bottom;
}
else { /* Nothing to do */ }
if(is_major_tick && ((LV_SCALE_MODE_HORIZONTAL_TOP == scale->mode) || (LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode))) {
major_len *= -1;
}
/* Draw tick lines to the right or top */
else if(!is_major_tick && (LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode ||
LV_SCALE_MODE_HORIZONTAL_TOP == scale->mode)) {
minor_len *= -1;
}
else { /* Nothing to do */ }
const int32_t tick_length = is_major_tick ? major_len : minor_len;
/* Setup the tick points */
if(LV_SCALE_MODE_VERTICAL_LEFT == scale->mode || LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode) {
/* Vertical position starts at y2 of the scale main line, we start at y2 because the ticks are drawn from bottom to top */
int32_t vertical_position = obj->coords.y2 - (pad_bottom + tick_pad_bottom);
if((scale->total_tick_count - 1U) == tick_idx) {
vertical_position = y_ofs;
}
/* Increment the tick offset depending of its index */
else if(0 != tick_idx) {
const int32_t scale_total_height = lv_obj_get_height(obj) - (pad_top + pad_bottom + tick_pad_top + tick_pad_bottom);
int32_t offset = ((int32_t) tick_idx * (int32_t) scale_total_height) / (int32_t)(
scale->total_tick_count - 1);
vertical_position -= offset;
}
else { /* Nothing to do */ }
tick_point_a->x = x_ofs - 1U; /* Move extra pixel out of scale boundary */
tick_point_a->y = vertical_position;
tick_point_b->x = tick_point_a->x - tick_length;
tick_point_b->y = vertical_position;
}
else {
/* Horizontal position starts at x1 of the scale main line */
int32_t horizontal_position = x_ofs;
/* Position the last tick at the x2 scale coordinate */
if((scale->total_tick_count - 1U) == tick_idx) {
horizontal_position = obj->coords.x2 - (pad_left + tick_pad_left);
}
/* Increment the tick offset depending of its index */
else if(0U != tick_idx) {
const int32_t scale_total_width = lv_obj_get_width(obj) - (pad_right + pad_left + tick_pad_right + tick_pad_left);
int32_t offset = ((int32_t) tick_idx * (int32_t) scale_total_width) / (int32_t)(
scale->total_tick_count - 1);
horizontal_position += offset;
}
else { /* Nothing to do */ }
tick_point_a->x = horizontal_position;
tick_point_a->y = y_ofs;
tick_point_b->x = horizontal_position;
tick_point_b->y = tick_point_a->y + tick_length;
}
}
else if(LV_SCALE_MODE_ROUND_OUTER == scale->mode || LV_SCALE_MODE_ROUND_INNER == scale->mode) {
lv_area_t scale_area;
lv_obj_get_content_coords(obj, &scale_area);
/* Find the center of the scale */
lv_point_t center_point;
const int32_t radius_edge = LV_MIN(lv_area_get_width(&scale_area) / 2U, lv_area_get_height(&scale_area) / 2U);
center_point.x = scale_area.x1 + radius_edge;
center_point.y = scale_area.y1 + radius_edge;
int32_t angle_upscale = ((tick_idx * scale->angle_range) * 10U) / (scale->total_tick_count - 1);
angle_upscale += scale->rotation * 10U;
/* Draw a little bit longer lines to be sure the mask will clip them correctly
* and to get a better precision. Adding the main line width to the calculation so we don't have gaps
* between the arc and the ticks */
int32_t point_closer_to_arc = 0;
int32_t adjusted_radio_with_tick_len = 0;
if(LV_SCALE_MODE_ROUND_INNER == scale->mode) {
point_closer_to_arc = radius_edge - main_line_dsc.width;
adjusted_radio_with_tick_len = point_closer_to_arc - (is_major_tick ? major_len : minor_len);
}
else if(LV_SCALE_MODE_ROUND_OUTER == scale->mode) {
point_closer_to_arc = radius_edge - main_line_dsc.width;
adjusted_radio_with_tick_len = point_closer_to_arc + (is_major_tick ? major_len : minor_len);
}
else { /* Nothing to do */ }
tick_point_a->x = center_point.x + point_closer_to_arc;
tick_point_a->y = center_point.y;
lv_point_transform(tick_point_a, angle_upscale, LV_SCALE_NONE, LV_SCALE_NONE, ¢er_point, false);
tick_point_b->x = center_point.x + adjusted_radio_with_tick_len;
tick_point_b->y = center_point.y;
lv_point_transform(tick_point_b, angle_upscale, LV_SCALE_NONE, LV_SCALE_NONE, ¢er_point, false);
}
else { /* Nothing to do */ }
}
/**
* Get coordinates for label
*
* @param obj pointer to a scale object
* @param label_dsc pointer to label descriptor
* @param tick_point pointer to reference tick
* @param label_coords pointer to label coordinates output
*/
static void scale_get_label_coords(lv_obj_t * obj, lv_draw_label_dsc_t * label_dsc, lv_point_t * tick_point,
lv_area_t * label_coords)
{
lv_scale_t * scale = (lv_scale_t *)obj;
/* Reserve appropriate size for the tick label */
lv_point_t label_size;
lv_text_get_size(&label_size, label_dsc->text,
label_dsc->font, label_dsc->letter_space, label_dsc->line_space, LV_COORD_MAX, LV_TEXT_FLAG_NONE);
/* Set the label draw area at some distance of the major tick */
if((LV_SCALE_MODE_HORIZONTAL_BOTTOM == scale->mode) || (LV_SCALE_MODE_HORIZONTAL_TOP == scale->mode)) {
label_coords->x1 = tick_point->x - (label_size.x / 2U);
label_coords->x2 = tick_point->x + (label_size.x / 2U);
if(LV_SCALE_MODE_HORIZONTAL_BOTTOM == scale->mode) {
label_coords->y1 = tick_point->y + lv_obj_get_style_pad_bottom(obj, LV_PART_INDICATOR);
label_coords->y2 = label_coords->y1 + label_size.y;
}
else {
label_coords->y2 = tick_point->y - lv_obj_get_style_pad_top(obj, LV_PART_INDICATOR);
label_coords->y1 = label_coords->y2 - label_size.y;
}
}
else if((LV_SCALE_MODE_VERTICAL_LEFT == scale->mode) || (LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode)) {
label_coords->y1 = tick_point->y - (label_size.y / 2U);
label_coords->y2 = tick_point->y + (label_size.y / 2U);
if(LV_SCALE_MODE_VERTICAL_LEFT == scale->mode) {
label_coords->x1 = tick_point->x - label_size.x - lv_obj_get_style_pad_left(obj, LV_PART_INDICATOR);
label_coords->x2 = tick_point->x - lv_obj_get_style_pad_left(obj, LV_PART_INDICATOR);
}
else {
label_coords->x1 = tick_point->x + lv_obj_get_style_pad_right(obj, LV_PART_INDICATOR);
label_coords->x2 = tick_point->x + label_size.x + lv_obj_get_style_pad_right(obj, LV_PART_INDICATOR);
}
}
else if(LV_SCALE_MODE_ROUND_OUTER == scale->mode || LV_SCALE_MODE_ROUND_INNER == scale->mode) {
label_coords->x1 = tick_point->x - (label_size.x / 2U);
label_coords->y1 = tick_point->y - (label_size.y / 2U);
label_coords->x2 = label_coords->x1 + label_size.x;
label_coords->y2 = label_coords->y1 + label_size.y;
}
else { /* Nothing to do */ }
}
/**
* Set line properties
*
* Checks if the line has a custom section configuration or not and sets the properties accordingly.
*
* @param obj pointer to a scale object
* @param line_dsc pointer to line descriptor
* @param items_section_style pointer to indicator section style
* @param part line part, example: LV_PART_INDICATOR, LV_PART_ITEMS, LV_PART_MAIN
*/
static void scale_set_line_properties(lv_obj_t * obj, lv_draw_line_dsc_t * line_dsc, lv_style_t * section_style,
uint32_t part)
{
if(section_style) {
lv_style_value_t value;
lv_result_t res;
/* Line width */
res = lv_style_get_prop(section_style, LV_STYLE_LINE_WIDTH, &value);
if(res == LV_RESULT_OK) {
line_dsc->width = (int32_t)value.num;
}
else {
line_dsc->width = lv_obj_get_style_line_width(obj, part);
}
/* Line color */
res = lv_style_get_prop(section_style, LV_STYLE_LINE_COLOR, &value);
if(res == LV_RESULT_OK) {
line_dsc->color = value.color;
}
else {
line_dsc->color = lv_obj_get_style_line_color(obj, part);
}
/* Line opa */
res = lv_style_get_prop(section_style, LV_STYLE_LINE_OPA, &value);
if(res == LV_RESULT_OK) {
line_dsc->opa = (lv_opa_t)value.num;
}
else {
line_dsc->opa = lv_obj_get_style_line_opa(obj, part);
}
}
else {
line_dsc->color = lv_obj_get_style_line_color(obj, part);
line_dsc->opa = lv_obj_get_style_line_opa(obj, part);
line_dsc->width = lv_obj_get_style_line_width(obj, part);
}
}
/**
* Set arc properties
*
* Checks if the arc has a custom section configuration or not and sets the properties accordingly.
*
* @param obj pointer to a scale object
* @param line_dsc pointer to arc descriptor
* @param items_section_style pointer to indicator section style
*/
static void scale_set_arc_properties(lv_obj_t * obj, lv_draw_arc_dsc_t * arc_dsc, lv_style_t * section_style)
{
if(section_style) {
lv_style_value_t value;
lv_result_t res;
/* Line width */
res = lv_style_get_prop(section_style, LV_STYLE_ARC_WIDTH, &value);
if(res == LV_RESULT_OK) {
arc_dsc->width = (int32_t)value.num;
}
else {
arc_dsc->width = lv_obj_get_style_line_width(obj, LV_PART_MAIN);
}
/* Line color */
res = lv_style_get_prop(section_style, LV_STYLE_ARC_COLOR, &value);
if(res == LV_RESULT_OK) {
arc_dsc->color = value.color;
}
else {
arc_dsc->color = lv_obj_get_style_line_color(obj, LV_PART_MAIN);
}
/* Line opa */
res = lv_style_get_prop(section_style, LV_STYLE_ARC_OPA, &value);
if(res == LV_RESULT_OK) {
arc_dsc->opa = (lv_opa_t)value.num;
}
else {
arc_dsc->opa = lv_obj_get_style_line_opa(obj, LV_PART_MAIN);
}
}
else {
arc_dsc->color = lv_obj_get_style_line_color(obj, LV_PART_MAIN);
arc_dsc->opa = lv_obj_get_style_line_opa(obj, LV_PART_MAIN);
arc_dsc->width = lv_obj_get_style_line_width(obj, LV_PART_MAIN);
}
}
/**
* Set indicator label properties
*
* Checks if the indicator has a custom section configuration or not and sets the properties accordingly.
*
* @param obj pointer to a scale object
* @param label_dsc pointer to label descriptor
* @param items_section_style pointer to indicator section style
*/
static void scale_set_indicator_label_properties(lv_obj_t * obj, lv_draw_label_dsc_t * label_dsc,
lv_style_t * indicator_section_style)
{
if(indicator_section_style) {
lv_style_value_t value;
lv_result_t res;
/* Text color */
res = lv_style_get_prop(indicator_section_style, LV_STYLE_TEXT_COLOR, &value);
if(res == LV_RESULT_OK) {
label_dsc->color = value.color;
}
else {
label_dsc->color = lv_obj_get_style_text_color(obj, LV_PART_INDICATOR);
}
/* Text opa */
res = lv_style_get_prop(indicator_section_style, LV_STYLE_TEXT_OPA, &value);
if(res == LV_RESULT_OK) {
label_dsc->opa = (lv_opa_t)value.num;
}
else {
label_dsc->opa = lv_obj_get_style_text_opa(obj, LV_PART_INDICATOR);
}
/* Text letter space */
res = lv_style_get_prop(indicator_section_style, LV_STYLE_TEXT_LETTER_SPACE, &value);
if(res == LV_RESULT_OK) {
label_dsc->letter_space = (int32_t)value.num;
}
else {
label_dsc->letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_INDICATOR);
}
/* Text font */
res = lv_style_get_prop(indicator_section_style, LV_STYLE_TEXT_FONT, &value);
if(res == LV_RESULT_OK) {
label_dsc->font = (const lv_font_t *)value.ptr;
}
else {
label_dsc->font = lv_obj_get_style_text_font(obj, LV_PART_INDICATOR);
}
}
else {
/* If label is not within a range then get the indicator style */
label_dsc->color = lv_obj_get_style_text_color(obj, LV_PART_INDICATOR);
label_dsc->opa = lv_obj_get_style_text_opa(obj, LV_PART_INDICATOR);
label_dsc->letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_INDICATOR);
label_dsc->font = lv_obj_get_style_text_font(obj, LV_PART_INDICATOR);
}
}
static void scale_find_section_tick_idx(lv_obj_t * obj)
{
lv_scale_t * scale = (lv_scale_t *)obj;
const int32_t min_out = scale->range_min;
const int32_t max_out = scale->range_max;
const uint32_t total_tick_count = scale->total_tick_count;
/* Section handling */
uint32_t tick_idx = 0;
for(tick_idx = 0; tick_idx < total_tick_count; tick_idx++) {
bool is_major_tick = false;
if(tick_idx % scale->major_tick_every == 0) is_major_tick = true;
const int32_t tick_value = lv_map(tick_idx, 0U, total_tick_count - 1, min_out, max_out);
lv_scale_section_t * section;
_LV_LL_READ_BACK(&scale->section_ll, section) {
if(section->minor_range <= tick_value && section->major_range >= tick_value) {
if(section->first_tick_idx_in_section == 255) {
section->first_tick_idx_in_section = tick_idx;
section->first_tick_idx_is_major = is_major_tick;
}
if(section->first_tick_idx_in_section != tick_idx) {
section->last_tick_idx_in_section = tick_idx;
section->last_tick_idx_is_major = is_major_tick;
}
}
else { /* Nothing to do */ }
}
}
}
/**
* Stores the width of the initial and last tick of the main line
*
* This width is used to compensate the main line drawing taking into consideration the widths of both ticks
*
* @param obj pointer to a scale object
* @param tick_idx index of the current tick
* @param is_major_tick true if tick_idx is a major tick
* @param major_tick_width width of the major tick
* @param minor_tick_width width of the minor tick
*/
static void scale_store_main_line_tick_width_compensation(lv_obj_t * obj, const uint32_t tick_idx,
const bool is_major_tick, const int32_t major_tick_width, const int32_t minor_tick_width)
{
lv_scale_t * scale = (lv_scale_t *)obj;
if(scale->total_tick_count == tick_idx) {
if((LV_SCALE_MODE_VERTICAL_LEFT == scale->mode) || (LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode)) {
scale->last_tick_width = is_major_tick ? major_tick_width : minor_tick_width;
}
else if((LV_SCALE_MODE_HORIZONTAL_BOTTOM == scale->mode) || (LV_SCALE_MODE_HORIZONTAL_TOP == scale->mode)) {
scale->first_tick_width = is_major_tick ? major_tick_width : minor_tick_width;
}
else if((LV_SCALE_MODE_ROUND_INNER == scale->mode) || (LV_SCALE_MODE_ROUND_OUTER == scale->mode)) {
/* TODO */
}
else { /* Nothing to do */ }
}
else if(0U == tick_idx) {
if((LV_SCALE_MODE_VERTICAL_LEFT == scale->mode) || (LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode)) {
scale->first_tick_width = is_major_tick ? major_tick_width : minor_tick_width;
}
else if((LV_SCALE_MODE_HORIZONTAL_BOTTOM == scale->mode) || (LV_SCALE_MODE_HORIZONTAL_TOP == scale->mode)) {
scale->last_tick_width = is_major_tick ? major_tick_width : minor_tick_width;
}
else if((LV_SCALE_MODE_ROUND_INNER == scale->mode) || (LV_SCALE_MODE_ROUND_OUTER == scale->mode)) {
/* TODO */
}
else { /* Nothing to do */ }
}
else { /* Nothing to do */ }
}
/**
* Sets the text of the tick label descriptor when using custom labels
*
* Sets the text pointer when valid custom label is available, otherwise set it to NULL.
*
* @param obj pointer to a scale object
* @param label_dsc pointer to the label descriptor
* @param major_tick_idx index of the current major tick
*/
static void scale_build_custom_label_text(lv_obj_t * obj, lv_draw_label_dsc_t * label_dsc,
const uint16_t major_tick_idx)
{
lv_scale_t * scale = (lv_scale_t *) obj;
/* Check if the scale has valid custom labels available,
* this avoids reading past txt_src array when the scale requires more tick labels than available */
if(major_tick_idx <= scale->custom_label_cnt) {
if(scale->txt_src[major_tick_idx - 1U]) {
label_dsc->text = scale->txt_src[major_tick_idx - 1U];
label_dsc->text_local = 0;
}
else {
label_dsc->text = NULL;
}
}
else {
label_dsc->text = NULL;
}
}
/**
* Stores tick width compensation information for main line sections
*
* @param obj pointer to a scale object
* @param is_major_tick Indicates if tick is major or not
* @param label_dsc pointer to the label descriptor
* @param major_tick_dsc pointer to the major_tick_dsc
* @param minor_tick_dsc pointer to the minor_tick_dsc
* @param tick_value Current tick value, used to know if tick_idx belongs to a section or not
* @param tick_idx Current tick index
* @param tick_point_a Pointer to tick point a
*/
static void scale_store_section_line_tick_width_compensation(lv_obj_t * obj, const bool is_major_tick,
lv_draw_label_dsc_t * label_dsc, lv_draw_line_dsc_t * major_tick_dsc, lv_draw_line_dsc_t * minor_tick_dsc,
const int32_t tick_value, const uint8_t tick_idx, lv_point_t * tick_point_a)
{
lv_scale_t * scale = (lv_scale_t *) obj;
lv_scale_section_t * section;
_LV_LL_READ_BACK(&scale->section_ll, section) {
if(section->minor_range <= tick_value && section->major_range >= tick_value) {
if(is_major_tick) {
scale_set_indicator_label_properties(obj, label_dsc, section->indicator_style);
scale_set_line_properties(obj, major_tick_dsc, section->indicator_style, LV_PART_INDICATOR);
}
else {
scale_set_line_properties(obj, minor_tick_dsc, section->items_style, LV_PART_ITEMS);
}
}
int32_t tmp_width = 0;
if(tick_idx == section->first_tick_idx_in_section) {
if(section->first_tick_idx_is_major) {
tmp_width = major_tick_dsc->width;
}
else {
tmp_width = minor_tick_dsc->width;
}
section->first_tick_in_section.y = tick_point_a->y;
/* Add 1px as adjustment if tmp_width is odd */
if(tmp_width & 0x01U) {
if(LV_SCALE_MODE_VERTICAL_LEFT == scale->mode || LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode) {
tmp_width += 1U;
}
else {
tmp_width -= 1U;
}
}
section->first_tick_in_section_width = tmp_width;
}
else if(tick_idx == section->last_tick_idx_in_section) {
if(section->last_tick_idx_is_major) {
tmp_width = major_tick_dsc->width;
}
else {
tmp_width = minor_tick_dsc->width;
}
section->last_tick_in_section.y = tick_point_a->y;
/* Add 1px as adjustment if tmp_width is odd */
if(tmp_width & 0x01U) {
if(LV_SCALE_MODE_VERTICAL_LEFT == scale->mode || LV_SCALE_MODE_VERTICAL_RIGHT == scale->mode) {
tmp_width -= 1U;
}
else {
tmp_width += 1U;
}
}
section->last_tick_in_section_width = tmp_width;
}
else { /* Nothing to do */ }
}
}
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/canvas/lv_canvas.c | /**
* @file lv_canvas.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_canvas.h"
#if LV_USE_CANVAS != 0
#include "../../misc/lv_assert.h"
#include "../../misc/lv_math.h"
#include "../../draw/lv_draw.h"
#include "../../core/lv_refr.h"
#include "../../display/lv_display.h"
#include "../../draw/sw/lv_draw_sw.h"
#include "../../stdlib/lv_string.h"
/*********************
* 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_image_class,
.name = "canvas",
};
/**********************
* 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, int32_t w, int32_t h, lv_color_format_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.header.stride = lv_draw_buf_width_to_stride(w, cf); /*Let LVGL calculate it automatically*/
canvas->dsc.data = buf;
canvas->dsc.data_size = w * h * lv_color_format_get_size(cf);
lv_image_set_src(obj, &canvas->dsc);
lv_cache_lock();
lv_cache_invalidate(lv_cache_find(&canvas->dsc, LV_CACHE_SRC_TYPE_PTR, 0, 0));
lv_cache_unlock();
}
void lv_canvas_set_px(lv_obj_t * obj, int32_t x, int32_t y, lv_color_t color, lv_opa_t opa)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_canvas_t * canvas = (lv_canvas_t *)obj;
if(LV_COLOR_FORMAT_IS_INDEXED(canvas->dsc.header.cf)) {
uint32_t stride = (canvas->dsc.header.w + 7) >> 3;
uint8_t * buf = (uint8_t *)canvas->dsc.data;
buf += 8;
buf += y * stride;
buf += x >> 3;
uint32_t bit = 7 - (x & 0x7);
uint32_t c_int = color.blue;
*buf &= ~(1 << bit);
*buf |= c_int << bit;
}
else if(canvas->dsc.header.cf == LV_COLOR_FORMAT_A8) {
uint8_t * buf = (uint8_t *)canvas->dsc.data;
buf += canvas->dsc.header.w * y + x;
*buf = opa;
}
else if(canvas->dsc.header.cf == LV_COLOR_FORMAT_RGB565) {
lv_color16_t * buf = (lv_color16_t *)canvas->dsc.data;
buf += canvas->dsc.header.w * y + x;
buf->red = color.red >> 3;
buf->green = color.green >> 2;
buf->blue = color.blue >> 3;
}
else if(canvas->dsc.header.cf == LV_COLOR_FORMAT_RGB888) {
uint8_t * buf = (uint8_t *)canvas->dsc.data;
buf += canvas->dsc.header.w * y * 3 + x * 3;
buf[2] = color.red;
buf[1] = color.green;
buf[0] = color.blue;
}
else if(canvas->dsc.header.cf == LV_COLOR_FORMAT_XRGB8888) {
uint8_t * buf = (uint8_t *)canvas->dsc.data;
buf += canvas->dsc.header.w * y * 4 + x * 4;
buf[2] = color.red;
buf[1] = color.green;
buf[0] = color.blue;
buf[3] = 0xFF;
}
else if(canvas->dsc.header.cf == LV_COLOR_FORMAT_ARGB8888) {
lv_color32_t * buf = (lv_color32_t *)canvas->dsc.data;
buf += canvas->dsc.header.w * y + x;
buf->red = color.red;
buf->green = color.green;
buf->blue = color.blue;
buf->alpha = opa;
}
lv_obj_invalidate(obj);
}
void lv_canvas_set_palette(lv_obj_t * obj, uint8_t id, lv_color32_t c)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_canvas_t * canvas = (lv_canvas_t *)obj;
lv_image_buf_set_palette(&canvas->dsc, id, c);
lv_obj_invalidate(obj);
}
/*=====================
* Getter functions
*====================*/
lv_color32_t lv_canvas_get_px(lv_obj_t * obj, int32_t x, int32_t y)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_canvas_t * canvas = (lv_canvas_t *)obj;
uint8_t px_size = lv_color_format_get_size(canvas->dsc.header.cf);
const uint8_t * px = canvas->dsc.data + canvas->dsc.header.w * y * px_size + x * px_size;
lv_color32_t ret;
switch(canvas->dsc.header.cf) {
case LV_COLOR_FORMAT_ARGB8888:
ret.red = px[0];
ret.green = px[1];
ret.blue = px[2];
ret.alpha = px[3];
break;
case LV_COLOR_FORMAT_RGB888:
case LV_COLOR_FORMAT_XRGB8888:
ret.red = px[0];
ret.green = px[1];
ret.blue = px[2];
ret.alpha = 0xFF;
break;
case LV_COLOR_FORMAT_RGB565: {
lv_color16_t * c16 = (lv_color16_t *) px;
ret.red = (c16[x].red * 2106) >> 8; /*To make it rounded*/
ret.green = (c16[x].green * 1037) >> 8;
ret.blue = (c16[x].blue * 2106) >> 8;
ret.alpha = 0xFF;
break;
}
case LV_COLOR_FORMAT_A8: {
lv_color_t alpha_color = lv_obj_get_style_image_recolor(obj, LV_PART_MAIN);
ret.red = alpha_color.red;
ret.green = alpha_color.green;
ret.blue = alpha_color.blue;
ret.alpha = px[0];
break;
}
default:
lv_memzero(&ret, sizeof(lv_color32_t));
break;
}
return ret;
}
lv_image_dsc_t * lv_canvas_get_image(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, int32_t x, int32_t y, int32_t w, int32_t h)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(to_copy);
lv_canvas_t * canvas = (lv_canvas_t *)obj;
if(x + w - 1 >= (int32_t)canvas->dsc.header.w || y + h - 1 >= (int32_t)canvas->dsc.header.h) {
LV_LOG_WARN("x or y out of the canvas");
return;
}
uint32_t px_size = lv_color_format_get_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;
int32_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_fill_bg(lv_obj_t * obj, lv_color_t color, lv_opa_t opa)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_image_dsc_t * dsc = lv_canvas_get_image(obj);
uint32_t x;
uint32_t y;
uint32_t stride = lv_draw_buf_width_to_stride(dsc->header.w, dsc->header.cf);
if(dsc->header.cf == LV_COLOR_FORMAT_RGB565) {
uint16_t c16 = lv_color_to_u16(color);
for(y = 0; y < dsc->header.h; y++) {
uint16_t * buf16 = (uint16_t *)(dsc->data + y * stride);
for(x = 0; x < dsc->header.w; x++) {
buf16[x] = c16;
}
}
}
else if(dsc->header.cf == LV_COLOR_FORMAT_XRGB8888 || dsc->header.cf == LV_COLOR_FORMAT_ARGB8888) {
uint32_t c32 = lv_color_to_u32(color);
if(dsc->header.cf == LV_COLOR_FORMAT_ARGB8888) {
c32 &= 0x00ffffff;
c32 |= opa << 24;
}
for(y = 0; y < dsc->header.h; y++) {
uint32_t * buf32 = (uint32_t *)(dsc->data + y * stride);
for(x = 0; x < dsc->header.w; x++) {
buf32[x] = c32;
}
}
}
else if(dsc->header.cf == LV_COLOR_FORMAT_RGB888) {
for(y = 0; y < dsc->header.h; y++) {
uint8_t * buf8 = (uint8_t *)(dsc->data + y * stride);
for(x = 0; x < dsc->header.w * 3; x += 3) {
buf8[x + 0] = color.blue;
buf8[x + 1] = color.green;
buf8[x + 2] = color.red;
}
}
}
else {
for(y = 0; y < dsc->header.h; y++) {
for(x = 0; x < dsc->header.w; x++) {
lv_canvas_set_px(obj, x, y, color, opa);
}
}
}
lv_obj_invalidate(obj);
}
void lv_canvas_init_layer(lv_obj_t * canvas, lv_layer_t * layer)
{
LV_ASSERT_NULL(canvas);
LV_ASSERT_NULL(layer);
lv_image_dsc_t * dsc = lv_canvas_get_image(canvas);
lv_area_t canvas_area = {0, 0, dsc->header.w - 1, dsc->header.h - 1};
lv_memzero(layer, sizeof(*layer));
layer->buf = lv_draw_buf_align((uint8_t *)dsc->data, dsc->header.cf);
layer->color_format = dsc->header.cf;
layer->buf_area = canvas_area;
layer->clip_area = canvas_area;
}
void lv_canvas_finish_layer(lv_obj_t * canvas, lv_layer_t * layer)
{
while(layer->draw_task_head) {
lv_draw_dispatch_wait_for_request();
lv_draw_dispatch_layer(lv_obj_get_disp(canvas), layer);
}
}
/**********************
* 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_COLOR_FORMAT_NATIVE;
canvas->dsc.header.h = 0;
canvas->dsc.header.w = 0;
canvas->dsc.data_size = 0;
canvas->dsc.data = NULL;
lv_image_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_cache_lock();
lv_cache_invalidate(lv_cache_find(&canvas->dsc, LV_CACHE_SRC_TYPE_PTR, 0, 0));
lv_cache_unlock();
}
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/canvas/lv_canvas.h | /**
* @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 "../image/lv_image.h"
#include "../../draw/lv_draw_image.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
extern const lv_obj_class_t lv_canvas_class;
/*Data of canvas*/
typedef struct {
lv_image_t img;
lv_image_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_image_color_format_get_px_size(cf) * w) / 8 * h)
* It can be allocated with `lv_malloc()` 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_IMAGE_CF_...`
*/
void lv_canvas_set_buffer(lv_obj_t * canvas, void * buf, int32_t w, int32_t h, lv_color_format_t cf);
void lv_canvas_set_px(lv_obj_t * obj, int32_t x, int32_t y, lv_color_t color, lv_opa_t opa);
/**
* Set the palette color of a canvas with index format. Valid only for `LV_IMAGE_CF_INDEXED1/2/4/8`
* @param canvas pointer to canvas object
* @param id the palette color to set:
* - for `LV_IMAGE_CF_INDEXED1`: 0..1
* - for `LV_IMAGE_CF_INDEXED2`: 0..3
* - for `LV_IMAGE_CF_INDEXED4`: 0..15
* - for `LV_IMAGE_CF_INDEXED8`: 0..255
* @param c the color to set
*/
void lv_canvas_set_palette(lv_obj_t * canvas, uint8_t id, lv_color32_t c);
/*=====================
* Getter functions
*====================*/
lv_color32_t lv_canvas_get_px(lv_obj_t * obj, int32_t x, int32_t y);
/**
* Get the image of the canvas as a pointer to an `lv_image_dsc_t` variable.
* @param canvas pointer to a canvas object
* @return pointer to the image descriptor.
*/
lv_image_dsc_t * lv_canvas_get_image(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, int32_t x, int32_t y, int32_t w,
int32_t h);
/**
* 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 * obj, lv_color_t color, lv_opa_t opa);
void lv_canvas_init_layer(lv_obj_t * canvas, lv_layer_t * layer);
void lv_canvas_finish_layer(lv_obj_t * canvas, lv_layer_t * layer);
/**********************
* MACROS
**********************/
#define LV_CANVAS_BUF_SIZE_TRUE_COLOR(w, h) LV_IMAGE_BUF_SIZE_TRUE_COLOR(w, h)
#define LV_CANVAS_BUF_SIZE_TRUE_COLOR_CHROMA_KEYED(w, h) LV_IMAGE_BUF_SIZE_TRUE_COLOR_CHROMA_KEYED(w, h)
#define LV_CANVAS_BUF_SIZE_TRUE_COLOR_ALPHA(w, h) LV_IMAGE_BUF_SIZE_TRUE_COLOR_ALPHA(w, h)
/*+ 1: to be sure no fractional row*/
#define LV_CANVAS_BUF_SIZE_ALPHA_1BIT(w, h) LV_IMAGE_BUF_SIZE_ALPHA_1BIT(w, h)
#define LV_CANVAS_BUF_SIZE_ALPHA_2BIT(w, h) LV_IMAGE_BUF_SIZE_ALPHA_2BIT(w, h)
#define LV_CANVAS_BUF_SIZE_ALPHA_4BIT(w, h) LV_IMAGE_BUF_SIZE_ALPHA_4BIT(w, h)
#define LV_CANVAS_BUF_SIZE_ALPHA_8BIT(w, h) LV_IMAGE_BUF_SIZE_ALPHA_8BIT(w, h)
/*4 * X: for palette*/
#define LV_CANVAS_BUF_SIZE_INDEXED_1BIT(w, h) LV_IMAGE_BUF_SIZE_INDEXED_1BIT(w, h)
#define LV_CANVAS_BUF_SIZE_INDEXED_2BIT(w, h) LV_IMAGE_BUF_SIZE_INDEXED_2BIT(w, h)
#define LV_CANVAS_BUF_SIZE_INDEXED_4BIT(w, h) LV_IMAGE_BUF_SIZE_INDEXED_4BIT(w, h)
#define LV_CANVAS_BUF_SIZE_INDEXED_8BIT(w, h) LV_IMAGE_BUF_SIZE_INDEXED_8BIT(w, h)
#endif /*LV_USE_CANVAS*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_CANVAS_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/spinbox/lv_spinbox.c | /**
* @file lv_spinbox.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_spinbox.h"
#if LV_USE_SPINBOX
#include "../../misc/lv_assert.h"
#include "../../indev/lv_indev.h"
#include "../../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_spinbox_class
#define LV_SPINBOX_MAX_DIGIT_COUNT_WITH_8BYTES (LV_SPINBOX_MAX_DIGIT_COUNT + 8U)
#define LV_SPINBOX_MAX_DIGIT_COUNT_WITH_4BYTES (LV_SPINBOX_MAX_DIGIT_COUNT + 4U)
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_spinbox_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_spinbox_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void lv_spinbox_updatevalue(lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_spinbox_class = {
.constructor_cb = lv_spinbox_constructor,
.event_cb = lv_spinbox_event,
.width_def = LV_DPI_DEF,
.instance_size = sizeof(lv_spinbox_t),
.editable = LV_OBJ_CLASS_EDITABLE_TRUE,
.base_class = &lv_textarea_class,
.name = "spinbox",
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_spinbox_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 spinbox value
* @param obj pointer to spinbox
* @param i value to be set
*/
void lv_spinbox_set_value(lv_obj_t * obj, int32_t i)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
if(i > spinbox->range_max) i = spinbox->range_max;
if(i < spinbox->range_min) i = spinbox->range_min;
spinbox->value = i;
lv_spinbox_updatevalue(obj);
}
/**
* Set spinbox rollover function
* @param spinbox pointer to spinbox
* @param b true or false to enable or disable (default)
*/
void lv_spinbox_set_rollover(lv_obj_t * obj, bool b)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
spinbox->rollover = b;
}
/**
* Set spinbox digit format (digit count and decimal format)
* @param spinbox pointer to spinbox
* @param digit_count number of digit excluding the decimal separator and the sign
* @param separator_position number of digit before the decimal point. If 0, decimal point is not
* shown
*/
void lv_spinbox_set_digit_format(lv_obj_t * obj, uint32_t digit_count, uint32_t separator_position)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
if(digit_count > LV_SPINBOX_MAX_DIGIT_COUNT) digit_count = LV_SPINBOX_MAX_DIGIT_COUNT;
if(separator_position >= digit_count) separator_position = 0;
if(digit_count < LV_SPINBOX_MAX_DIGIT_COUNT) {
const int64_t max_val = lv_pow(10, digit_count);
if(spinbox->range_max > max_val - 1) spinbox->range_max = max_val - 1;
if(spinbox->range_min < -max_val + 1) spinbox->range_min = -max_val + 1;
}
spinbox->digit_count = digit_count;
spinbox->dec_point_pos = separator_position;
lv_spinbox_updatevalue(obj);
}
/**
* Set spinbox step
* @param spinbox pointer to spinbox
* @param step steps on increment/decrement
*/
void lv_spinbox_set_step(lv_obj_t * obj, uint32_t step)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
spinbox->step = step;
lv_spinbox_updatevalue(obj);
}
/**
* Set spinbox value range
* @param spinbox pointer to spinbox
* @param range_min maximum value, inclusive
* @param range_max minimum value, inclusive
*/
void lv_spinbox_set_range(lv_obj_t * obj, int32_t range_min, int32_t range_max)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
spinbox->range_max = range_max;
spinbox->range_min = range_min;
if(spinbox->value > spinbox->range_max) spinbox->value = spinbox->range_max;
if(spinbox->value < spinbox->range_min) spinbox->value = spinbox->range_min;
lv_spinbox_updatevalue(obj);
}
/**
* Set cursor position to a specific digit for edition
* @param spinbox pointer to spinbox
* @param pos selected position in spinbox
*/
void lv_spinbox_set_cursor_pos(lv_obj_t * obj, uint32_t pos)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
const int32_t step_limit = LV_MAX(spinbox->range_max, LV_ABS(spinbox->range_min));
const int32_t new_step = lv_pow(10, pos);
if(pos <= 0) spinbox->step = 1;
else if(new_step <= step_limit) spinbox->step = new_step;
lv_spinbox_updatevalue(obj);
}
/**
* Set direction of digit step when clicking an encoder button while in editing mode
* @param spinbox pointer to spinbox
* @param direction the direction (LV_DIR_RIGHT or LV_DIR_LEFT)
*/
void lv_spinbox_set_digit_step_direction(lv_obj_t * obj, lv_dir_t direction)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
spinbox->digit_step_dir = direction;
lv_spinbox_updatevalue(obj);
}
/*=====================
* Getter functions
*====================*/
/**
* Get the spinbox numeral value (user has to convert to float according to its digit format)
* @param obj pointer to spinbox
* @return value integer value of the spinbox
*/
int32_t lv_spinbox_get_value(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
return spinbox->value;
}
/**
* Get the spinbox step value (user has to convert to float according to its digit format)
* @param obj pointer to spinbox
* @return value integer step value of the spinbox
*/
int32_t lv_spinbox_get_step(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
return spinbox->step;
}
/*=====================
* Other functions
*====================*/
/**
* Select next lower digit for edition
* @param obj pointer to spinbox
*/
void lv_spinbox_step_next(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
const int32_t new_step = spinbox->step / 10;
spinbox->step = (new_step > 0) ? new_step : 1;
lv_spinbox_updatevalue(obj);
}
/**
* Select next higher digit for edition
* @param obj pointer to spinbox
*/
void lv_spinbox_step_prev(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
const int32_t step_limit = LV_MAX(spinbox->range_max, LV_ABS(spinbox->range_min));
const int32_t new_step = spinbox->step * 10;
if(new_step <= step_limit) spinbox->step = new_step;
lv_spinbox_updatevalue(obj);
}
/**
* Get spinbox rollover function status
* @param obj pointer to spinbox
*/
bool lv_spinbox_get_rollover(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
return spinbox->rollover;
}
/**
* Increment spinbox value by one step
* @param obj pointer to spinbox
*/
void lv_spinbox_increment(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
int32_t v = spinbox->value;
/* Special mode when zero crossing. E.g -3+10 should be 3, not 7.
* Pretend we are on -7 now.*/
if((spinbox->value < 0) && (spinbox->value + spinbox->step) > 0) {
v = -(spinbox->step + spinbox->value);
}
if(v + spinbox->step <= spinbox->range_max) {
v += spinbox->step;
}
else {
/*Rollover?*/
if((spinbox->rollover) && (spinbox->value == spinbox->range_max))
v = spinbox->range_min;
else
v = spinbox->range_max;
}
if(v != spinbox->value) {
spinbox->value = v;
lv_spinbox_updatevalue(obj);
}
}
/**
* Decrement spinbox value by one step
* @param obj pointer to spinbox
*/
void lv_spinbox_decrement(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
int32_t v = spinbox->value;
/* Special mode when zero crossing. E.g 3-10 should be -3, not -7.
* Pretend we are on 7 now.*/
if((spinbox->value > 0) && (spinbox->value - spinbox->step) < 0) {
v = spinbox->step - spinbox->value;
}
if(v - spinbox->step >= spinbox->range_min) {
v -= spinbox->step;
}
else {
/*Rollover?*/
if((spinbox->rollover) && (spinbox->value == spinbox->range_min))
v = spinbox->range_max;
else
v = spinbox->range_min;
}
if(v != spinbox->value) {
spinbox->value = v;
lv_spinbox_updatevalue(obj);
}
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_spinbox_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_LOG_TRACE("begin");
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
/*Initialize the allocated 'ext'*/
spinbox->value = 0;
spinbox->dec_point_pos = 0;
spinbox->digit_count = 5;
spinbox->step = 1;
spinbox->range_max = 99999;
spinbox->range_min = -99999;
spinbox->rollover = false;
spinbox->digit_step_dir = LV_DIR_RIGHT;
lv_textarea_set_one_line(obj, true);
lv_textarea_set_cursor_click_pos(obj, true);
lv_spinbox_updatevalue(obj);
LV_LOG_TRACE("Spinbox constructor finished");
}
static void lv_spinbox_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
/*Call the ancestor's event handler*/
lv_result_t res = LV_RESULT_OK;
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RESULT_OK) return;
const lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
if(code == LV_EVENT_RELEASED) {
/*If released with an ENCODER then move to the next digit*/
lv_indev_t * indev = lv_indev_active();
if(lv_indev_get_type(indev) == LV_INDEV_TYPE_ENCODER && lv_group_get_editing(lv_obj_get_group(obj))) {
if(spinbox->digit_count > 1) {
if(spinbox->digit_step_dir == LV_DIR_RIGHT) {
if(spinbox->step > 1) {
lv_spinbox_step_next(obj);
}
else {
/*Restart from the MSB*/
spinbox->step = lv_pow(10, spinbox->digit_count - 2);
lv_spinbox_step_prev(obj);
}
}
else {
if(spinbox->step < lv_pow(10, spinbox->digit_count - 1)) {
lv_spinbox_step_prev(obj);
}
else {
/*Restart from the LSB*/
spinbox->step = 10;
lv_spinbox_step_next(obj);
}
}
}
}
/*The cursor has been positioned to a digit.
* Set `step` accordingly*/
else {
const char * txt = lv_textarea_get_text(obj);
const size_t txt_len = lv_strlen(txt);
/* Check cursor position */
/* Cursor is in '.' digit */
if(txt[spinbox->ta.cursor.pos] == '.') {
lv_textarea_cursor_left(obj);
}
/* Cursor is already in the right-most digit */
else if(spinbox->ta.cursor.pos == (uint32_t)txt_len) {
lv_textarea_set_cursor_pos(obj, txt_len - 1);
}
/* Cursor is already in the left-most digit AND range_min is negative */
else if(spinbox->ta.cursor.pos == 0 && spinbox->range_min < 0) {
lv_textarea_set_cursor_pos(obj, 1);
}
/* Handle spinbox with decimal point (spinbox->dec_point_pos != 0) */
uint32_t cp = spinbox->ta.cursor.pos;
if(spinbox->ta.cursor.pos > spinbox->dec_point_pos && spinbox->dec_point_pos != 0) cp--;
const size_t len = spinbox->digit_count - 1;
uint32_t pos = len - cp;
if(spinbox->range_min < 0) pos++;
spinbox->step = 1;
uint32_t i;
for(i = 0; i < pos; i++) spinbox->step *= 10;
}
}
else if(code == LV_EVENT_KEY) {
lv_indev_type_t indev_type = lv_indev_get_type(lv_indev_active());
uint32_t c = *((uint32_t *)lv_event_get_param(e)); /*uint32_t because can be UTF-8*/
if(c == LV_KEY_RIGHT) {
if(indev_type == LV_INDEV_TYPE_ENCODER)
lv_spinbox_increment(obj);
else
lv_spinbox_step_next(obj);
}
else if(c == LV_KEY_LEFT) {
if(indev_type == LV_INDEV_TYPE_ENCODER)
lv_spinbox_decrement(obj);
else
lv_spinbox_step_prev(obj);
}
else if(c == LV_KEY_UP) {
lv_spinbox_increment(obj);
}
else if(c == LV_KEY_DOWN) {
lv_spinbox_decrement(obj);
}
else {
lv_textarea_add_char(obj, c);
}
}
}
static void lv_spinbox_updatevalue(lv_obj_t * obj)
{
lv_spinbox_t * spinbox = (lv_spinbox_t *)obj;
/* LV_SPINBOX_MAX_DIGIT_COUNT_WITH_8BYTES (18): Max possible digit_count value (15) + sign + decimal point + NULL terminator */
char textarea_txt[LV_SPINBOX_MAX_DIGIT_COUNT_WITH_8BYTES] = {0U};
char * buf_p = textarea_txt;
uint32_t cur_shift_left = 0;
if(spinbox->range_min < 0) { // hide sign if there are only positive values
/*Add the sign*/
(*buf_p) = spinbox->value >= 0 ? '+' : '-';
buf_p++;
}
else {
/*Cursor need shift to left*/
cur_shift_left++;
}
/*Convert the numbers to string (the sign is already handled so always convert positive number)*/
char digits[LV_SPINBOX_MAX_DIGIT_COUNT_WITH_4BYTES];
lv_snprintf(digits, LV_SPINBOX_MAX_DIGIT_COUNT_WITH_4BYTES, "%" LV_PRId32, LV_ABS(spinbox->value));
/*Add leading zeros*/
int32_t i;
const size_t digits_len = lv_strlen(digits);
const int leading_zeros_cnt = spinbox->digit_count - digits_len;
if(leading_zeros_cnt) {
for(i = (int32_t) digits_len; i >= 0; i--) {
digits[i + leading_zeros_cnt] = digits[i];
}
/* NOTE: Substitute with memset? */
for(i = 0; i < leading_zeros_cnt; i++) {
digits[i] = '0';
}
}
/*Add the decimal part*/
const uint32_t intDigits = (spinbox->dec_point_pos == 0) ? spinbox->digit_count : spinbox->dec_point_pos;
for(i = 0; i < (int32_t)intDigits && digits[i] != '\0'; i++) {
(*buf_p) = digits[i];
buf_p++;
}
/*Insert the decimal point*/
if(spinbox->dec_point_pos) {
(*buf_p) = '.';
buf_p++;
for(/*Leave i*/; i < spinbox->digit_count && digits[i] != '\0'; i++) {
(*buf_p) = digits[i];
buf_p++;
}
}
/*Refresh the text*/
lv_textarea_set_text(obj, (char *)textarea_txt);
/*Set the cursor position*/
int32_t step = spinbox->step;
uint32_t cur_pos = (uint32_t)spinbox->digit_count;
while(step >= 10) {
step /= 10;
cur_pos--;
}
if(cur_pos > intDigits) cur_pos++; /*Skip the decimal point*/
cur_pos -= cur_shift_left;
lv_textarea_set_cursor_pos(obj, cur_pos);
}
#endif /*LV_USE_SPINBOX*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/spinbox/lv_spinbox.h | /**
* @file lv_spinbox.h
*
*/
#ifndef LV_SPINBOX_H
#define LV_SPINBOX_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../textarea/lv_textarea.h"
#if LV_USE_SPINBOX
/*Testing of dependencies*/
#if LV_USE_TEXTAREA == 0
#error "lv_spinbox: lv_ta is required. Enable it in lv_conf.h (LV_USE_TEXTAREA 1) "
#endif
/*********************
* DEFINES
*********************/
#define LV_SPINBOX_MAX_DIGIT_COUNT 10
/**********************
* TYPEDEFS
**********************/
/*Data of spinbox*/
typedef struct {
lv_textarea_t ta; /*Ext. of ancestor*/
/*New data for this type*/
int32_t value;
int32_t range_max;
int32_t range_min;
int32_t step;
uint32_t digit_count : 4;
uint32_t dec_point_pos : 4; /*if 0, there is no separator and the number is an integer*/
uint32_t rollover : 1; /* Set to true for rollover functionality*/
uint32_t digit_step_dir : 2; /* the direction the digit will step on encoder button press when editing*/
} lv_spinbox_t;
extern const lv_obj_class_t lv_spinbox_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a Spinbox object
* @param parent pointer to an object, it will be the parent of the new spinbox
* @return pointer to the created spinbox
*/
lv_obj_t * lv_spinbox_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set spinbox value
* @param obj pointer to spinbox
* @param i value to be set
*/
void lv_spinbox_set_value(lv_obj_t * obj, int32_t i);
/**
* Set spinbox rollover function
* @param obj pointer to spinbox
* @param b true or false to enable or disable (default)
*/
void lv_spinbox_set_rollover(lv_obj_t * obj, bool b);
/**
* Set spinbox digit format (digit count and decimal format)
* @param obj pointer to spinbox
* @param digit_count number of digit excluding the decimal separator and the sign
* @param separator_position number of digit before the decimal point. If 0, decimal point is not
* shown
*/
void lv_spinbox_set_digit_format(lv_obj_t * obj, uint32_t digit_count, uint32_t separator_position);
/**
* Set spinbox step
* @param obj pointer to spinbox
* @param step steps on increment/decrement. Can be 1, 10, 100, 1000, etc the digit that will change.
*/
void lv_spinbox_set_step(lv_obj_t * obj, uint32_t step);
/**
* Set spinbox value range
* @param obj pointer to spinbox
* @param range_min maximum value, inclusive
* @param range_max minimum value, inclusive
*/
void lv_spinbox_set_range(lv_obj_t * obj, int32_t range_min, int32_t range_max);
/**
* Set cursor position to a specific digit for edition
* @param obj pointer to spinbox
* @param pos selected position in spinbox
*/
void lv_spinbox_set_cursor_pos(lv_obj_t * obj, uint32_t pos);
/**
* Set direction of digit step when clicking an encoder button while in editing mode
* @param obj pointer to spinbox
* @param direction the direction (LV_DIR_RIGHT or LV_DIR_LEFT)
*/
void lv_spinbox_set_digit_step_direction(lv_obj_t * obj, lv_dir_t direction);
/*=====================
* Getter functions
*====================*/
/**
* Get spinbox rollover function status
* @param obj pointer to spinbox
*/
bool lv_spinbox_get_rollover(lv_obj_t * obj);
/**
* Get the spinbox numeral value (user has to convert to float according to its digit format)
* @param obj pointer to spinbox
* @return value integer value of the spinbox
*/
int32_t lv_spinbox_get_value(lv_obj_t * obj);
/**
* Get the spinbox step value (user has to convert to float according to its digit format)
* @param obj pointer to spinbox
* @return value integer step value of the spinbox
*/
int32_t lv_spinbox_get_step(lv_obj_t * obj);
/*=====================
* Other functions
*====================*/
/**
* Select next lower digit for edition by dividing the step by 10
* @param obj pointer to spinbox
*/
void lv_spinbox_step_next(lv_obj_t * obj);
/**
* Select next higher digit for edition by multiplying the step by 10
* @param obj pointer to spinbox
*/
void lv_spinbox_step_prev(lv_obj_t * obj);
/**
* Increment spinbox value by one step
* @param obj pointer to spinbox
*/
void lv_spinbox_increment(lv_obj_t * obj);
/**
* Decrement spinbox value by one step
* @param obj pointer to spinbox
*/
void lv_spinbox_decrement(lv_obj_t * obj);
/**********************
* MACROS
**********************/
/* It was ambiguous in MicroPython. See https://github.com/lvgl/lvgl/issues/3301
* TODO remove in v9*/
#define lv_spinbox_set_pos lv_spinbox_set_cursor_pos
#endif /*LV_USE_SPINBOX*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_SPINBOX_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/keyboard/lv_keyboard.h | /**
* @file lv_keyboard.h
*
*/
#ifndef LV_KEYBOARD_H
#define LV_KEYBOARD_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../buttonmatrix/lv_buttonmatrix.h"
#if LV_USE_KEYBOARD
/*Testing of dependencies*/
#if LV_USE_BTNMATRIX == 0
#error "lv_kb: lv_btnm is required. Enable it in lv_conf.h (LV_USE_BTNMATRIX 1) "
#endif
#if LV_USE_TEXTAREA == 0
#error "lv_kb: lv_ta is required. Enable it in lv_conf.h (LV_USE_TEXTAREA 1) "
#endif
/*********************
* DEFINES
*********************/
#define LV_KEYBOARD_CTRL_BUTTON_FLAGS (LV_BUTTONMATRIX_CTRL_NO_REPEAT | LV_BUTTONMATRIX_CTRL_CLICK_TRIG | LV_BUTTONMATRIX_CTRL_CHECKED)
/**********************
* TYPEDEFS
**********************/
/** Current keyboard mode.*/
enum _lv_keyboard_mode_t {
LV_KEYBOARD_MODE_TEXT_LOWER,
LV_KEYBOARD_MODE_TEXT_UPPER,
LV_KEYBOARD_MODE_SPECIAL,
LV_KEYBOARD_MODE_NUMBER,
LV_KEYBOARD_MODE_USER_1,
LV_KEYBOARD_MODE_USER_2,
LV_KEYBOARD_MODE_USER_3,
LV_KEYBOARD_MODE_USER_4,
#if LV_USE_ARABIC_PERSIAN_CHARS == 1
LV_KEYBOARD_MODE_TEXT_ARABIC
#endif
};
#ifdef DOXYGEN
typedef _lv_keyboard_mode_t lv_keyboard_mode_t;
#else
typedef uint8_t lv_keyboard_mode_t;
#endif /*DOXYGEN*/
/*Data of keyboard*/
typedef struct {
lv_buttonmatrix_t btnm;
lv_obj_t * ta; /*Pointer to the assigned text area*/
lv_keyboard_mode_t mode; /*Key map type*/
uint8_t popovers : 1; /*Show button titles in popovers on press*/
} lv_keyboard_t;
extern const lv_obj_class_t lv_keyboard_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a Keyboard object
* @param parent pointer to an object, it will be the parent of the new keyboard
* @return pointer to the created keyboard
*/
lv_obj_t * lv_keyboard_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Assign a Text Area to the Keyboard. The pressed characters will be put there.
* @param kb pointer to a Keyboard object
* @param ta pointer to a Text Area object to write there
*/
void lv_keyboard_set_textarea(lv_obj_t * kb, lv_obj_t * ta);
/**
* Set a new a mode (text or number map)
* @param kb pointer to a Keyboard object
* @param mode the mode from 'lv_keyboard_mode_t'
*/
void lv_keyboard_set_mode(lv_obj_t * kb, lv_keyboard_mode_t mode);
/**
* Show the button title in a popover when pressed.
* @param kb pointer to a Keyboard object
* @param en whether "popovers" mode is enabled
*/
void lv_keyboard_set_popovers(lv_obj_t * kb, bool en);
/**
* Set a new map for the keyboard
* @param kb pointer to a Keyboard object
* @param mode keyboard map to alter 'lv_keyboard_mode_t'
* @param map pointer to a string array to describe the map.
* See 'lv_buttonmatrix_set_map()' for more info.
* @param ctrl_map
*/
void lv_keyboard_set_map(lv_obj_t * kb, lv_keyboard_mode_t mode, const char * map[],
const lv_buttonmatrix_ctrl_t ctrl_map[]);
/*=====================
* Getter functions
*====================*/
/**
* Assign a Text Area to the Keyboard. The pressed characters will be put there.
* @param kb pointer to a Keyboard object
* @return pointer to the assigned Text Area object
*/
lv_obj_t * lv_keyboard_get_textarea(const lv_obj_t * kb);
/**
* Set a new a mode (text or number map)
* @param kb pointer to a Keyboard object
* @return the current mode from 'lv_keyboard_mode_t'
*/
lv_keyboard_mode_t lv_keyboard_get_mode(const lv_obj_t * kb);
/**
* Tell whether "popovers" mode is enabled or not.
* @param obj pointer to a Keyboard object
* @return true: "popovers" mode is enabled; false: disabled
*/
bool lv_buttonmatrix_get_popovers(const lv_obj_t * obj);
/**
* Get the current map of a keyboard
* @param kb pointer to a keyboard object
* @return the current map
*/
static inline const char ** lv_keyboard_get_map_array(const lv_obj_t * kb)
{
return lv_buttonmatrix_get_map(kb);
}
/**
* Get the index of the lastly "activated" button by the user (pressed, released, focused etc)
* Useful in 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_BUTTONMATRIX_BUTTON_NONE: if unset)
*/
static inline uint32_t lv_keyboard_get_selected_button(const lv_obj_t * obj)
{
return lv_buttonmatrix_get_selected_button(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
*/
static inline const char * lv_keyboard_get_button_text(const lv_obj_t * obj, uint32_t btn_id)
{
return lv_buttonmatrix_get_button_text(obj, btn_id);
}
/*=====================
* Other functions
*====================*/
/**
* Default keyboard event to add characters to the Text area and change the map.
* If a custom `event_cb` is added to the keyboard this function can be called from it to handle the
* button clicks
* @param e the triggering event
*/
void lv_keyboard_def_event_cb(lv_event_t * e);
/**********************
* MACROS
**********************/
#endif /*LV_USE_KEYBOARD*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_KEYBOARD_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/keyboard/lv_keyboard.c |
/**
* @file lv_keyboard.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_keyboard.h"
#if LV_USE_KEYBOARD
#include "../textarea/lv_textarea.h"
#include "../../misc/lv_assert.h"
#include "../../stdlib/lv_string.h"
#include <stdlib.h>
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_keyboard_class
#define LV_KB_BTN(width) LV_BUTTONMATRIX_CTRL_POPOVER | width
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_keyboard_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_keyboard_update_map(lv_obj_t * obj);
static void lv_keyboard_update_ctrl_map(lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_keyboard_class = {
.constructor_cb = lv_keyboard_constructor,
.width_def = LV_PCT(100),
.height_def = LV_PCT(50),
.instance_size = sizeof(lv_keyboard_t),
.editable = 1,
.base_class = &lv_buttonmatrix_class,
.name = "keyboard",
};
static const char * const default_kb_map_lc[] = {"1#", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", LV_SYMBOL_BACKSPACE, "\n",
"ABC", "a", "s", "d", "f", "g", "h", "j", "k", "l", LV_SYMBOL_NEW_LINE, "\n",
"_", "-", "z", "x", "c", "v", "b", "n", "m", ".", ",", ":", "\n",
LV_SYMBOL_KEYBOARD,
#if LV_USE_ARABIC_PERSIAN_CHARS == 1
"أب",
#endif
LV_SYMBOL_LEFT, " ", LV_SYMBOL_RIGHT, LV_SYMBOL_OK, ""
};
static const lv_buttonmatrix_ctrl_t default_kb_ctrl_lc_map[] = {
LV_KEYBOARD_CTRL_BUTTON_FLAGS | 5, LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_BUTTONMATRIX_CTRL_CHECKED | 7,
LV_KEYBOARD_CTRL_BUTTON_FLAGS | 6, LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_BUTTONMATRIX_CTRL_CHECKED | 7,
LV_BUTTONMATRIX_CTRL_CHECKED | LV_KB_BTN(1), LV_BUTTONMATRIX_CTRL_CHECKED | LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_BUTTONMATRIX_CTRL_CHECKED | LV_KB_BTN(1), LV_BUTTONMATRIX_CTRL_CHECKED | LV_KB_BTN(1), LV_BUTTONMATRIX_CTRL_CHECKED | LV_KB_BTN(1),
LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2,
#if LV_USE_ARABIC_PERSIAN_CHARS == 1
LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2,
#endif
LV_BUTTONMATRIX_CTRL_CHECKED | 2, 6, LV_BUTTONMATRIX_CTRL_CHECKED | 2, LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2
};
static const char * const default_kb_map_uc[] = {"1#", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", LV_SYMBOL_BACKSPACE, "\n",
"abc", "A", "S", "D", "F", "G", "H", "J", "K", "L", LV_SYMBOL_NEW_LINE, "\n",
"_", "-", "Z", "X", "C", "V", "B", "N", "M", ".", ",", ":", "\n",
LV_SYMBOL_CLOSE,
#if LV_USE_ARABIC_PERSIAN_CHARS == 1
"أب",
#endif
LV_SYMBOL_LEFT, " ", LV_SYMBOL_RIGHT, LV_SYMBOL_OK, ""
};
static const lv_buttonmatrix_ctrl_t default_kb_ctrl_uc_map[] = {
LV_KEYBOARD_CTRL_BUTTON_FLAGS | 5, LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_KB_BTN(4), LV_BUTTONMATRIX_CTRL_CHECKED | 7,
LV_KEYBOARD_CTRL_BUTTON_FLAGS | 6, LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_KB_BTN(3), LV_BUTTONMATRIX_CTRL_CHECKED | 7,
LV_BUTTONMATRIX_CTRL_CHECKED | LV_KB_BTN(1), LV_BUTTONMATRIX_CTRL_CHECKED | LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_BUTTONMATRIX_CTRL_CHECKED | LV_KB_BTN(1), LV_BUTTONMATRIX_CTRL_CHECKED | LV_KB_BTN(1), LV_BUTTONMATRIX_CTRL_CHECKED | LV_KB_BTN(1),
LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2,
#if LV_USE_ARABIC_PERSIAN_CHARS == 1
LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2,
#endif
LV_BUTTONMATRIX_CTRL_CHECKED | 2, 6, LV_BUTTONMATRIX_CTRL_CHECKED | 2, LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2
};
#if LV_USE_ARABIC_PERSIAN_CHARS == 1
static const char * const default_kb_map_ar[] = {
"1#", "ض", "ص", "ث", "ق", "ف", "غ", "ع", "ه", "خ", "ح", "ج", "\n",
"ش", "س", "ي", "ب", "ل", "ا", "ت", "ن", "م", "ك", "ط", LV_SYMBOL_BACKSPACE, "\n",
"ذ", "ء", "ؤ", "ر", "ى", "ة", "و", "ز", "ظ", "د", "ز", "ظ", "د", "\n",
LV_SYMBOL_CLOSE, "abc", LV_SYMBOL_LEFT, " ", LV_SYMBOL_RIGHT, LV_SYMBOL_NEW_LINE, LV_SYMBOL_OK, ""
};
static const lv_buttonmatrix_ctrl_t default_kb_ctrl_ar_map[] = {
LV_KEYBOARD_CTRL_BUTTON_FLAGS | 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2, LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2, 2, 6, 2, 3, LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2
};
#endif
static const char * const default_kb_map_spec[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", LV_SYMBOL_BACKSPACE, "\n",
"abc", "+", "&", "/", "*", "=", "%", "!", "?", "#", "<", ">", "\n",
"\\", "@", "$", "(", ")", "{", "}", "[", "]", ";", "\"", "'", "\n",
LV_SYMBOL_KEYBOARD,
#if LV_USE_ARABIC_PERSIAN_CHARS == 1
"أب",
#endif
LV_SYMBOL_LEFT, " ", LV_SYMBOL_RIGHT, LV_SYMBOL_OK, ""
};
static const lv_buttonmatrix_ctrl_t default_kb_ctrl_spec_map[] = {
LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_BUTTONMATRIX_CTRL_CHECKED | 2,
LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2, LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1),
LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1), LV_KB_BTN(1),
LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2,
#if LV_USE_ARABIC_PERSIAN_CHARS == 1
LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2,
#endif
LV_BUTTONMATRIX_CTRL_CHECKED | 2, 6, LV_BUTTONMATRIX_CTRL_CHECKED | 2, LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2
};
static const char * const default_kb_map_num[] = {"1", "2", "3", LV_SYMBOL_KEYBOARD, "\n",
"4", "5", "6", LV_SYMBOL_OK, "\n",
"7", "8", "9", LV_SYMBOL_BACKSPACE, "\n",
"+/-", "0", ".", LV_SYMBOL_LEFT, LV_SYMBOL_RIGHT, ""
};
static const lv_buttonmatrix_ctrl_t default_kb_ctrl_num_map[] = {
1, 1, 1, LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2,
1, 1, 1, LV_KEYBOARD_CTRL_BUTTON_FLAGS | 2,
1, 1, 1, 2,
1, 1, 1, 1, 1
};
static const char * * kb_map[10] = {
(const char * *)default_kb_map_lc,
(const char * *)default_kb_map_uc,
(const char * *)default_kb_map_spec,
(const char * *)default_kb_map_num,
(const char * *)default_kb_map_lc,
(const char * *)default_kb_map_lc,
(const char * *)default_kb_map_lc,
(const char * *)default_kb_map_lc,
#if LV_USE_ARABIC_PERSIAN_CHARS == 1
(const char * *)default_kb_map_ar,
#endif
(const char * *)NULL
};
static const lv_buttonmatrix_ctrl_t * kb_ctrl[10] = {
default_kb_ctrl_lc_map,
default_kb_ctrl_uc_map,
default_kb_ctrl_spec_map,
default_kb_ctrl_num_map,
default_kb_ctrl_lc_map,
default_kb_ctrl_lc_map,
default_kb_ctrl_lc_map,
default_kb_ctrl_lc_map,
#if LV_USE_ARABIC_PERSIAN_CHARS == 1
default_kb_ctrl_ar_map,
#endif
NULL
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Create a Keyboard object
* @param parent pointer to an object, it will be the parent of the new keyboard
* @return pointer to the created keyboard
*/
lv_obj_t * lv_keyboard_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(&lv_keyboard_class, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*=====================
* Setter functions
*====================*/
/**
* Assign a Text Area to the Keyboard. The pressed characters will be put there.
* @param kb pointer to a Keyboard object
* @param ta pointer to a Text Area object to write there
*/
void lv_keyboard_set_textarea(lv_obj_t * obj, lv_obj_t * ta)
{
if(ta) {
LV_ASSERT_OBJ(ta, &lv_textarea_class);
}
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_keyboard_t * keyboard = (lv_keyboard_t *)obj;
/*Hide the cursor of the old Text area if cursor management is enabled*/
if(keyboard->ta) {
lv_obj_remove_state(obj, LV_STATE_FOCUSED);
}
keyboard->ta = ta;
/*Show the cursor of the new Text area if cursor management is enabled*/
if(keyboard->ta) {
lv_obj_add_flag(obj, LV_STATE_FOCUSED);
}
}
/**
* Set a new a mode (text or number map)
* @param kb pointer to a Keyboard object
* @param mode the mode from 'lv_keyboard_mode_t'
*/
void lv_keyboard_set_mode(lv_obj_t * obj, lv_keyboard_mode_t mode)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_keyboard_t * keyboard = (lv_keyboard_t *)obj;
if(keyboard->mode == mode) return;
keyboard->mode = mode;
lv_keyboard_update_map(obj);
}
/**
* Show the button title in a popover when pressed.
* @param kb pointer to a Keyboard object
* @param en whether "popovers" mode is enabled
*/
void lv_keyboard_set_popovers(lv_obj_t * obj, bool en)
{
lv_keyboard_t * keyboard = (lv_keyboard_t *)obj;
if(keyboard->popovers == en) {
return;
}
keyboard->popovers = en;
lv_keyboard_update_ctrl_map(obj);
}
/**
* Set a new map for the keyboard
* @param kb pointer to a Keyboard object
* @param mode keyboard map to alter 'lv_keyboard_mode_t'
* @param map pointer to a string array to describe the map.
* See 'lv_buttonmatrix_set_map()' for more info.
*/
void lv_keyboard_set_map(lv_obj_t * obj, lv_keyboard_mode_t mode, const char * map[],
const lv_buttonmatrix_ctrl_t ctrl_map[])
{
kb_map[mode] = map;
kb_ctrl[mode] = ctrl_map;
lv_keyboard_update_map(obj);
}
/*=====================
* Getter functions
*====================*/
/**
* Assign a Text Area to the Keyboard. The pressed characters will be put there.
* @param kb pointer to a Keyboard object
* @return pointer to the assigned Text Area object
*/
lv_obj_t * lv_keyboard_get_textarea(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_keyboard_t * keyboard = (lv_keyboard_t *)obj;
return keyboard->ta;
}
/**
* Set a new a mode (text or number map)
* @param kb pointer to a Keyboard object
* @return the current mode from 'lv_keyboard_mode_t'
*/
lv_keyboard_mode_t lv_keyboard_get_mode(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_keyboard_t * keyboard = (lv_keyboard_t *)obj;
return keyboard->mode;
}
/**
* Tell whether "popovers" mode is enabled or not.
* @param kb pointer to a Keyboard object
* @return true: "popovers" mode is enabled; false: disabled
*/
bool lv_buttonmatrix_get_popovers(const lv_obj_t * obj)
{
lv_keyboard_t * keyboard = (lv_keyboard_t *)obj;
return keyboard->popovers;
}
/*=====================
* Other functions
*====================*/
/**
* Default keyboard event to add characters to the Text area and change the map.
* If a custom `event_cb` is added to the keyboard this function can be called from it to handle the
* button clicks
* @param kb pointer to a keyboard
* @param event the triggering event
*/
void lv_keyboard_def_event_cb(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_keyboard_t * keyboard = (lv_keyboard_t *)obj;
uint32_t btn_id = lv_buttonmatrix_get_selected_button(obj);
if(btn_id == LV_BUTTONMATRIX_BUTTON_NONE) return;
const char * txt = lv_buttonmatrix_get_button_text(obj, btn_id);
if(txt == NULL) return;
if(strcmp(txt, "abc") == 0) {
keyboard->mode = LV_KEYBOARD_MODE_TEXT_LOWER;
lv_buttonmatrix_set_map(obj, kb_map[LV_KEYBOARD_MODE_TEXT_LOWER]);
lv_keyboard_update_ctrl_map(obj);
return;
}
#if LV_USE_ARABIC_PERSIAN_CHARS == 1
else if(strcmp(txt, "أب") == 0) {
keyboard->mode = LV_KEYBOARD_MODE_TEXT_ARABIC;
lv_buttonmatrix_set_map(obj, kb_map[LV_KEYBOARD_MODE_TEXT_ARABIC]);
lv_keyboard_update_ctrl_map(obj);
return;
}
#endif
else if(strcmp(txt, "ABC") == 0) {
keyboard->mode = LV_KEYBOARD_MODE_TEXT_UPPER;
lv_buttonmatrix_set_map(obj, kb_map[LV_KEYBOARD_MODE_TEXT_UPPER]);
lv_keyboard_update_ctrl_map(obj);
return;
}
else if(strcmp(txt, "1#") == 0) {
keyboard->mode = LV_KEYBOARD_MODE_SPECIAL;
lv_buttonmatrix_set_map(obj, kb_map[LV_KEYBOARD_MODE_SPECIAL]);
lv_keyboard_update_ctrl_map(obj);
return;
}
else if(strcmp(txt, LV_SYMBOL_CLOSE) == 0 || strcmp(txt, LV_SYMBOL_KEYBOARD) == 0) {
lv_result_t res = lv_obj_send_event(obj, LV_EVENT_CANCEL, NULL);
if(res != LV_RESULT_OK) return;
if(keyboard->ta) {
res = lv_obj_send_event(keyboard->ta, LV_EVENT_CANCEL, NULL);
if(res != LV_RESULT_OK) return;
}
return;
}
else if(strcmp(txt, LV_SYMBOL_OK) == 0) {
lv_result_t res = lv_obj_send_event(obj, LV_EVENT_READY, NULL);
if(res != LV_RESULT_OK) return;
if(keyboard->ta) {
res = lv_obj_send_event(keyboard->ta, LV_EVENT_READY, NULL);
if(res != LV_RESULT_OK) return;
}
return;
}
/*Add the characters to the text area if set*/
if(keyboard->ta == NULL) return;
if(strcmp(txt, "Enter") == 0 || strcmp(txt, LV_SYMBOL_NEW_LINE) == 0) {
lv_textarea_add_char(keyboard->ta, '\n');
if(lv_textarea_get_one_line(keyboard->ta)) {
lv_result_t res = lv_obj_send_event(keyboard->ta, LV_EVENT_READY, NULL);
if(res != LV_RESULT_OK) return;
}
}
else if(strcmp(txt, LV_SYMBOL_LEFT) == 0) {
lv_textarea_cursor_left(keyboard->ta);
}
else if(strcmp(txt, LV_SYMBOL_RIGHT) == 0) {
lv_textarea_cursor_right(keyboard->ta);
}
else if(strcmp(txt, LV_SYMBOL_BACKSPACE) == 0) {
lv_textarea_delete_char(keyboard->ta);
}
else if(strcmp(txt, "+/-") == 0) {
uint32_t cur = lv_textarea_get_cursor_pos(keyboard->ta);
const char * ta_txt = lv_textarea_get_text(keyboard->ta);
if(ta_txt[0] == '-') {
lv_textarea_set_cursor_pos(keyboard->ta, 1);
lv_textarea_delete_char(keyboard->ta);
lv_textarea_add_char(keyboard->ta, '+');
lv_textarea_set_cursor_pos(keyboard->ta, cur);
}
else if(ta_txt[0] == '+') {
lv_textarea_set_cursor_pos(keyboard->ta, 1);
lv_textarea_delete_char(keyboard->ta);
lv_textarea_add_char(keyboard->ta, '-');
lv_textarea_set_cursor_pos(keyboard->ta, cur);
}
else {
lv_textarea_set_cursor_pos(keyboard->ta, 0);
lv_textarea_add_char(keyboard->ta, '-');
lv_textarea_set_cursor_pos(keyboard->ta, cur + 1);
}
}
else {
lv_textarea_add_text(keyboard->ta, txt);
}
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_keyboard_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_obj_remove_flag(obj, LV_OBJ_FLAG_CLICK_FOCUSABLE);
lv_keyboard_t * keyboard = (lv_keyboard_t *)obj;
keyboard->ta = NULL;
keyboard->mode = LV_KEYBOARD_MODE_TEXT_LOWER;
keyboard->popovers = 0;
lv_obj_align(obj, LV_ALIGN_BOTTOM_MID, 0, 0);
lv_obj_add_event(obj, lv_keyboard_def_event_cb, LV_EVENT_VALUE_CHANGED, NULL);
lv_obj_set_style_base_dir(obj, LV_BASE_DIR_LTR, 0);
lv_keyboard_update_map(obj);
}
/**
* Update the key and control map for the current mode
* @param obj pointer to a keyboard object
*/
static void lv_keyboard_update_map(lv_obj_t * obj)
{
lv_keyboard_t * keyboard = (lv_keyboard_t *)obj;
lv_buttonmatrix_set_map(obj, kb_map[keyboard->mode]);
lv_keyboard_update_ctrl_map(obj);
}
/**
* Update the control map for the current mode
* @param obj pointer to a keyboard object
*/
static void lv_keyboard_update_ctrl_map(lv_obj_t * obj)
{
lv_keyboard_t * keyboard = (lv_keyboard_t *)obj;
if(keyboard->popovers) {
/*Apply the current control map (already includes LV_BUTTONMATRIX_CTRL_POPOVER flags)*/
lv_buttonmatrix_set_ctrl_map(obj, kb_ctrl[keyboard->mode]);
}
else {
/*Make a copy of the current control map*/
lv_buttonmatrix_t * btnm = (lv_buttonmatrix_t *)obj;
lv_buttonmatrix_ctrl_t * ctrl_map = lv_malloc(btnm->btn_cnt * sizeof(lv_buttonmatrix_ctrl_t));
lv_memcpy(ctrl_map, kb_ctrl[keyboard->mode], sizeof(lv_buttonmatrix_ctrl_t) * btnm->btn_cnt);
/*Remove all LV_BUTTONMATRIX_CTRL_POPOVER flags*/
uint32_t i;
for(i = 0; i < btnm->btn_cnt; i++) {
ctrl_map[i] &= (~LV_BUTTONMATRIX_CTRL_POPOVER);
}
/*Apply new control map and clean up*/
lv_buttonmatrix_set_ctrl_map(obj, ctrl_map);
lv_free(ctrl_map);
}
}
#endif /*LV_USE_KEYBOARD*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/label/lv_label.h | /**
* @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_text.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
#if LV_WIDGETS_HAS_DEFAULT_VALUE
#define LV_LABEL_DEFAULT_TEXT "Text"
#else
#define LV_LABEL_DEFAULT_TEXT ""
#endif
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_mode_t {
LV_LABEL_LONG_WRAP, /**< Keep the object width, wrap lines longer than object width 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*/
};
#ifdef DOXYGEN
typedef _lv_label_long_mode_t lv_label_long_mode_t;
#else
typedef uint8_t lv_label_long_mode_t;
#endif /*DOXYGEN*/
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 size_cache; /*Text size cache*/
lv_point_t offset; /*Text draw position offset*/
lv_label_long_mode_t long_mode : 3; /*Determine 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_SCROLL)*/
uint8_t dot_tmp_alloc : 1; /*1: dot is allocated, 0: dot directly holds up to 4 chars*/
uint8_t invalid_size_cache : 1; /*1: Recalculate size and update cache*/
} lv_label_t;
extern const lv_obj_class_t lv_label_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a label object
* @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 obj 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 obj 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 obj 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 text longer than the object size
* @param obj 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 obj 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_selection_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_selection_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 char_id 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_in 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 obj pointer to a 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 obj 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*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/label/lv_label.c | /**
* @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 "../../display/lv_display.h"
#include "../../draw/lv_draw.h"
#include "../../misc/lv_color.h"
#include "../../misc/lv_math.h"
#include "../../misc/lv_bidi.h"
#include "../../misc/lv_text_ap.h"
#include "../../stdlib/lv_sprintf.h"
#include "../../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_label_class
#define LV_LABEL_DEF_SCROLL_SPEED (lv_display_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 size_t get_text_length(const char * text);
static void copy_text_to_label(lv_label_t * label, const char * text);
static lv_text_flag_t get_label_flags(lv_label_t * label);
static void calculate_x_coordinate(int32_t * x, const lv_text_align_t align, const char * txt,
uint32_t length, const lv_font_t * font, int32_t letter_space, lv_area_t * txt_coords);
/**********************
* 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,
.name = "label",
};
/**********************
* 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;
const size_t text_len = get_text_length(text);
/*If set its own text then reallocate it (maybe its size changed)*/
if(label->text == text && label->static_txt == 0) {
label->text = lv_realloc(label->text, text_len);
LV_ASSERT_MALLOC(label->text);
if(label->text == NULL) return;
#if LV_USE_ARABIC_PERSIAN_CHARS
_lv_text_ap_proc(label->text, label->text);
#endif
}
else {
/*Free the old text*/
if(label->text != NULL && label->static_txt == 0) {
lv_free(label->text);
label->text = NULL;
}
label->text = lv_malloc(text_len);
LV_ASSERT_MALLOC(label->text);
if(label->text == NULL) return;
copy_text_to_label(label, text);
/*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_free(label->text);
label->text = NULL;
}
va_list args;
va_start(args, fmt);
label->text = _lv_text_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_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_delete(obj, set_ofs_x_anim);
lv_anim_delete(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 ? 1 : 0;
/*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_selection_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_selection_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;
}
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);
const 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;
default:
break;
}
return;
}
lv_text_flag_t flag = get_label_flags(label);
if(lv_obj_get_style_width(obj, LV_PART_MAIN) == LV_SIZE_CONTENT && !obj->w_layout) flag |= LV_TEXT_FLAG_FIT;
const uint32_t byte_id = _lv_text_encoded_get_byte_id(txt, char_id);
/*Search the line of the index letter*/
const int32_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
const int32_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_MAIN);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
const int32_t letter_height = lv_font_get_line_height(font);
lv_area_t txt_coords;
lv_obj_get_content_coords(obj, &txt_coords);
const int32_t max_w = lv_area_get_width(&txt_coords);
int32_t y = 0;
uint32_t line_start = 0;
uint32_t new_line_start = 0;
while(txt[new_line_start] != '\0') {
new_line_start += _lv_text_get_next_line(&txt[line_start], font, letter_space, max_w, NULL, 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_text_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_text_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*/
int32_t x = lv_text_get_width(bidi_txt, visual_byte_pos, font, letter_space);
if(char_id != line_start) x += letter_space;
uint32_t length = new_line_start - line_start;
calculate_x_coordinate(&x, align, bidi_txt, length, font, letter_space, &txt_coords);
pos->x = x;
pos->y = y;
#if LV_USE_BIDI
if(mutable_bidi_txt) lv_free(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;
int32_t max_w = lv_area_get_width(&txt_coords);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
const int32_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
const int32_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_MAIN);
const int32_t letter_height = lv_font_get_line_height(font);
int32_t y = 0;
lv_text_flag_t flag = get_label_flags(label);
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_text_get_next_line(&txt[line_start], font, letter_space, max_w, NULL, 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_text_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;
}
char * bidi_txt;
#if LV_USE_BIDI
bidi_txt = lv_malloc(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*/
int32_t x = 0;
const lv_text_align_t align = lv_obj_calculate_style_text_align(obj, LV_PART_MAIN, label->text);
uint32_t length = new_line_start - line_start;
calculate_x_coordinate(&x, align, bidi_txt, length, font, letter_space, &txt_coords);
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_text_encoded_letter_next_2(bidi_txt, &letter, &letter_next, &i);
int32_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;
}
}
uint32_t logical_pos;
#if LV_USE_BIDI
/*Handle Bidi*/
uint32_t cid = _lv_text_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_free(bidi_txt);
#else
logical_pos = _lv_text_encoded_get_char_id(bidi_txt, i);
#endif
return logical_pos + _lv_text_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;
const int32_t max_w = lv_area_get_width(&txt_coords);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
const int32_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
const int32_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_MAIN);
const int32_t letter_height = lv_font_get_line_height(font);
lv_text_flag_t flag = get_label_flags(label);
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*/
int32_t y = 0;
while(txt[line_start] != '\0') {
new_line_start += _lv_text_get_next_line(&txt[line_start], font, letter_space, max_w, NULL, 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*/
const lv_text_align_t align = lv_obj_calculate_style_text_align(obj, LV_PART_MAIN, label->text);
int32_t x = 0;
if(align == LV_TEXT_ALIGN_CENTER) {
const int32_t line_w = lv_text_get_width(&txt[line_start], new_line_start - line_start, font, letter_space);
x += lv_area_get_width(&txt_coords) / 2 - line_w / 2;
}
else if(align == LV_TEXT_ALIGN_RIGHT) {
const int32_t line_w = lv_text_get_width(&txt[line_start], new_line_start - line_start, font, letter_space);
x += lv_area_get_width(&txt_coords) - line_w;
}
int32_t last_x = 0;
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_text_encoded_letter_next_2(txt, &letter, &letter_next, &i);
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;
}
}
const 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 = lv_strlen(label->text);
size_t ins_len = lv_strlen(txt);
size_t new_len = ins_len + old_len;
label->text = lv_realloc(label->text, new_len + 1);
LV_ASSERT_MALLOC(label->text);
if(label->text == NULL) return;
if(pos == LV_LABEL_POS_LAST) {
pos = _lv_text_get_encoded_length(label->text);
}
_lv_text_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) return;
lv_obj_invalidate(obj);
char * label_txt = lv_label_get_text(obj);
/*Delete the characters*/
_lv_text_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_remove_flag(obj, LV_OBJ_FLAG_CLICKABLE);
lv_label_set_long_mode(obj, LV_LABEL_LONG_WRAP);
lv_label_set_text(obj, LV_LABEL_DEFAULT_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_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);
/*Call the ancestor's event handler*/
const lv_result_t res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RESULT_OK) return;
const 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) || (code == LV_EVENT_SIZE_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);
const int32_t font_h = lv_font_get_line_height(font);
lv_event_set_ext_draw_size(e, font_h / 4);
}
else if(code == LV_EVENT_GET_SELF_SIZE) {
lv_label_t * label = (lv_label_t *)obj;
if(label->invalid_size_cache) {
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
int32_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_MAIN);
int32_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;
int32_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_text_get_size(&label->size_cache, label->text, font, letter_space, line_space, w, flag);
label->invalid_size_cache = false;
}
lv_point_t * self_size = lv_event_get_param(e);
self_size->x = LV_MAX(self_size->x, label->size_cache.x);
self_size->y = LV_MAX(self_size->y, label->size_cache.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;
lv_layer_t * layer = lv_event_get_layer(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) 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.text = label->text;
label_draw_dsc.ofs_x = label->offset.x;
label_draw_dsc.ofs_y = label->offset.y;
#if LV_LABEL_LONG_TXT_HINT
if(label->long_mode != LV_LABEL_LONG_SCROLL_CIRCULAR && lv_area_get_height(&txt_coords) >= LV_LABEL_HINT_HEIGHT_LIMIT) {
label_draw_dsc.hint = &label->hint;
}
#endif
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 SCROLL and SCROLL_CIRCULAR mode the CENTER and RIGHT are pointless, so remove them.
* (In addition, they will create misalignment in this situation)*/
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_text_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;
}
}
lv_area_t txt_clip;
bool is_common = _lv_area_intersect(&txt_clip, &txt_coords, &layer->clip_area);
if(!is_common) {
return;
}
if(label->long_mode == LV_LABEL_LONG_WRAP) {
int32_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) {
const lv_area_t clip_area_ori = layer->clip_area;
layer->clip_area = txt_clip;
lv_draw_label(layer, &label_draw_dsc, &txt_coords);
layer->clip_area = clip_area_ori;
}
else {
lv_draw_label(layer, &label_draw_dsc, &txt_coords);
}
lv_area_t clip_area_ori = layer->clip_area;
layer->clip_area = txt_clip;
if(label->long_mode == LV_LABEL_LONG_SCROLL_CIRCULAR) {
lv_point_t size;
lv_text_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(layer, &label_draw_dsc, &txt_coords);
}
/*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(layer, &label_draw_dsc, &txt_coords);
}
}
layer->clip_area = clip_area_ori;
}
static void overwrite_anim_property(lv_anim_t * dest, const lv_anim_t * src, lv_label_long_mode_t mode)
{
switch(mode) {
case LV_LABEL_LONG_SCROLL:
/** If the dest animation is already running, overwrite is not allowed */
if(dest->act_time <= 0)
dest->act_time = src->act_time;
dest->repeat_cnt = src->repeat_cnt;
dest->repeat_delay = src->repeat_delay;
dest->ready_cb = src->ready_cb;
dest->playback_delay = src->playback_delay;
break;
case LV_LABEL_LONG_SCROLL_CIRCULAR:
/** If the dest animation is already running, overwrite is not allowed */
if(dest->act_time <= 0)
dest->act_time = src->act_time;
dest->repeat_cnt = src->repeat_cnt;
dest->repeat_delay = src->repeat_delay;
dest->ready_cb = src->ready_cb;
break;
default:
break;
}
}
/**
* 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
label->invalid_size_cache = true;
lv_area_t txt_coords;
lv_obj_get_content_coords(obj, &txt_coords);
int32_t max_w = lv_area_get_width(&txt_coords);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
int32_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
int32_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) 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_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 animation*/
if(label->long_mode == LV_LABEL_LONG_SCROLL) {
const lv_anim_t * anim_template = lv_obj_get_style_anim(obj, LV_PART_MAIN);
uint32_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)) {
int32_t start = 0;
int32_t end = 0;
#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(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;
}
#else
end = lv_area_get_width(&txt_coords) - size.x;
#endif
lv_anim_set_values(&a, start, end);
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);
/*If a template animation exists, overwrite some property*/
if(anim_template)
overwrite_anim_property(&a, anim_template, label->long_mode);
lv_anim_start(&a);
hor_anim = true;
}
else {
/*Delete the offset animation if not required*/
lv_anim_delete(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);
/*If a template animation exists, overwrite some property*/
if(anim_template)
overwrite_anim_property(&a, anim_template, label->long_mode);
lv_anim_start(&a);
}
else {
/*Delete the offset animation if not required*/
lv_anim_delete(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) {
const lv_anim_t * anim_template = lv_obj_get_style_anim(obj, LV_PART_MAIN);
uint32_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 a template animation exists, overwrite some property*/
if(anim_template) {
overwrite_anim_property(&a, anim_template, label->long_mode);
}
else if(act_time < a.time) {
a.act_time = act_time; /*To keep the old position when the label text is updated mid-scrolling*/
a.early_apply = 0;
}
lv_anim_start(&a);
hor_anim = true;
}
else {
/*Delete the offset animation if not required*/
lv_anim_delete(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 a template animation exists, overwrite some property*/
if(anim_template) {
overwrite_anim_property(&a, anim_template, label->long_mode);
}
else if(act_time < a.time) {
a.act_time = act_time; /*To keep the old position when the label text is updated mid-scrolling*/
a.early_apply = 0;
}
lv_anim_start(&a);
}
else {
/*Delete the offset animation if not required*/
lv_anim_delete(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(size.y <= lv_font_get_line_height(font)) { /*No dots are required for one-line texts*/
label->dot_end = LV_LABEL_DOT_END_INV;
}
else if(_lv_text_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;
int32_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 = lv_strlen(label->text);
uint32_t byte_id = _lv_text_encoded_get_byte_id(label->text, letter_id);
while(byte_id + LV_LABEL_DOT_NUM > txt_len) {
_lv_text_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_text_encoded_size(&label->text[byte_id]);
_lv_text_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;
const uint32_t letter_i = label->dot_end - LV_LABEL_DOT_NUM;
const uint32_t byte_i = _lv_text_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_malloc(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_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);
}
static size_t get_text_length(const char * text)
{
size_t len = 0;
#if LV_USE_ARABIC_PERSIAN_CHARS
len = _lv_text_ap_calc_bytes_cnt(text);
#else
len = lv_strlen(text) + 1;
#endif
return len;
}
static void copy_text_to_label(lv_label_t * label, const char * text)
{
#if LV_USE_ARABIC_PERSIAN_CHARS
_lv_text_ap_proc(text, label->text);
#else
lv_strcpy(label->text, text);
#endif
}
static lv_text_flag_t get_label_flags(lv_label_t * label)
{
lv_text_flag_t flag = LV_TEXT_FLAG_NONE;
if(label->recolor) flag |= LV_TEXT_FLAG_RECOLOR;
if(label->expand) flag |= LV_TEXT_FLAG_EXPAND;
return flag;
}
/* Function created because of this pattern be used in multiple functions */
static void calculate_x_coordinate(int32_t * x, const lv_text_align_t align, const char * txt, uint32_t length,
const lv_font_t * font, int32_t letter_space, lv_area_t * txt_coords)
{
if(align == LV_TEXT_ALIGN_CENTER) {
const int32_t line_w = lv_text_get_width(txt, length, font, letter_space);
*x += lv_area_get_width(txt_coords) / 2 - line_w / 2;
}
else if(align == LV_TEXT_ALIGN_RIGHT) {
const int32_t line_w = lv_text_get_width(txt, length, font, letter_space);
*x += lv_area_get_width(txt_coords) - line_w;
}
else {
/* Nothing to do */
}
}
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/animimage/lv_animimage.h | /**
* @file lv_animimg.h
*
*/
#ifndef LV_ANIM_IMAGE_H
#define LV_ANIM_IMAGE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../image/lv_image.h"
#if LV_USE_ANIMIMG != 0
/*Testing of dependencies*/
#if LV_USE_IMG == 0
#error "lv_animimg: lv_img is required. Enable it in lv_conf.h (LV_USE_IMG 1)"
#endif
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
extern const lv_obj_class_t lv_animimg_class;
/*Data of image*/
typedef struct {
lv_image_t img;
lv_anim_t anim;
/*picture sequence */
const void ** dsc;
int8_t pic_count;
} lv_animimg_t;
/*Image parts*/
enum _lv_animimg_part_t {
LV_ANIM_IMAGE_PART_MAIN,
};
#ifdef DOXYGEN
typedef _lv_animimg_part_t lv_animimg_part_t;
#else
typedef uint8_t lv_animimg_part_t;
#endif
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create an animation image objects
* @param parent pointer to an object, it will be the parent of the new button
* @return pointer to the created animation image object
*/
lv_obj_t * lv_animimg_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set the image animation images source.
* @param img pointer to an animation image object
* @param dsc pointer to a series images
* @param num images' number
*/
void lv_animimg_set_src(lv_obj_t * img, const void * dsc[], size_t num);
/**
* Startup the image animation.
* @param obj pointer to an animation image object
*/
void lv_animimg_start(lv_obj_t * obj);
/**
* Set the image animation duration time. unit:ms
* @param img pointer to an animation image object
* @param duration the duration
*/
void lv_animimg_set_duration(lv_obj_t * img, uint32_t duration);
/**
* Set the image animation repeatedly play times.
* @param img pointer to an animation image object
* @param count the number of times to repeat the animation
*/
void lv_animimg_set_repeat_count(lv_obj_t * img, uint32_t count);
/*=====================
* Getter functions
*====================*/
/**
* Get the image animation images source.
* @param img pointer to an animation image object
* @return a pointer that will point to a series images
*/
const void ** lv_animimg_get_src(lv_obj_t * img);
/**
* Get the image animation images source.
* @param img pointer to an animation image object
* @return the number of source images
*/
uint8_t lv_animimg_get_src_count(lv_obj_t * img);
/**
* Get the image animation duration time. unit:ms
* @param img pointer to an animation image object
* @return the animation duration time
*/
uint32_t lv_animimg_get_duration(lv_obj_t * img);
/**
* Get the image animation repeat play times.
* @param img pointer to an animation image object
* @return the repeat count
*/
uint32_t lv_animimg_get_repeat_count(lv_obj_t * img);
#endif /*LV_USE_ANIMIMG*/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*LV_ANIM_IMAGE_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/animimage/lv_animimage.c | /**
* @file lv_animimg.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_animimage.h"
#if LV_USE_ANIMIMG != 0
/*Testing of dependencies*/
#if LV_USE_IMG == 0
#error "lv_animimg: lv_img is required. Enable it in lv_conf.h (LV_USE_IMG 1) "
#endif
#include "../../draw/lv_image_decoder.h"
#include "../../misc/lv_assert.h"
#include "../../misc/lv_fs.h"
#include "../../misc/lv_text.h"
#include "../../misc/lv_math.h"
#include "../../misc/lv_log.h"
#include "../../misc/lv_anim.h"
/*********************
* DEFINES
*********************/
#define LV_OBJX_NAME "lv_animimg"
#define MY_CLASS &lv_animimg_class
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void index_change(lv_obj_t * obj, int32_t index);
static void lv_animimg_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_animimg_class = {
.constructor_cb = lv_animimg_constructor,
.instance_size = sizeof(lv_animimg_t),
.base_class = &lv_image_class,
.name = "animimg",
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_animimg_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(&lv_animimg_class, parent);
lv_obj_class_init_obj(obj);
return obj;
}
void lv_animimg_set_src(lv_obj_t * obj, const void * dsc[], size_t num)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_animimg_t * animimg = (lv_animimg_t *)obj;
animimg->dsc = dsc;
animimg->pic_count = num;
lv_anim_set_values(&animimg->anim, 0, (int32_t)num - 1);
}
void lv_animimg_start(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_animimg_t * animimg = (lv_animimg_t *)obj;
lv_anim_start(&animimg->anim);
}
/*=====================
* Setter functions
*====================*/
void lv_animimg_set_duration(lv_obj_t * obj, uint32_t duration)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_animimg_t * animimg = (lv_animimg_t *)obj;
lv_anim_set_time(&animimg->anim, duration);
lv_anim_set_playback_delay(&animimg->anim, duration);
}
void lv_animimg_set_repeat_count(lv_obj_t * obj, uint32_t count)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_animimg_t * animimg = (lv_animimg_t *)obj;
lv_anim_set_repeat_count(&animimg->anim, count);
}
/*=====================
* Getter functions
*====================*/
const void ** lv_animimg_get_src(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_animimg_t * animimg = (lv_animimg_t *)obj;
return animimg->dsc;
}
uint8_t lv_animimg_get_src_count(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_animimg_t * animimg = (lv_animimg_t *)obj;
return animimg->pic_count;
}
uint32_t lv_animimg_get_duration(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_animimg_t * animimg = (lv_animimg_t *)obj;
return lv_anim_get_time(&animimg->anim);
}
uint32_t lv_animimg_get_repeat_count(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_animimg_t * animimg = (lv_animimg_t *)obj;
return lv_anim_get_repeat_count(&animimg->anim);
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_animimg_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_TRACE_OBJ_CREATE("begin");
LV_UNUSED(class_p);
lv_animimg_t * animimg = (lv_animimg_t *)obj;
animimg->dsc = NULL;
animimg->pic_count = -1;
/*initial animation*/
lv_anim_init(&animimg->anim);
lv_anim_set_var(&animimg->anim, obj);
lv_anim_set_time(&animimg->anim, 30);
lv_anim_set_exec_cb(&animimg->anim, (lv_anim_exec_xcb_t)index_change);
lv_anim_set_values(&animimg->anim, 0, 1);
lv_anim_set_repeat_count(&animimg->anim, LV_ANIM_REPEAT_INFINITE);
}
static void index_change(lv_obj_t * obj, int32_t index)
{
int32_t idx;
lv_animimg_t * animimg = (lv_animimg_t *)obj;
idx = index % animimg->pic_count;
lv_image_set_src(obj, animimg->dsc[idx]);
}
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/menu/lv_menu.c | /**
* @file lv_menu.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_menu.h"
#if LV_USE_MENU
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_menu_class
#include "../../core/lv_obj.h"
#include "../../layouts/lv_layout.h"
#include "../../stdlib/lv_string.h"
#include "../label/lv_label.h"
#include "../button/lv_button.h"
#include "../image/lv_image.h"
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_menu_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_menu_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_menu_page_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_menu_page_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_menu_cont_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_menu_section_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
const lv_obj_class_t lv_menu_class = {
.constructor_cb = lv_menu_constructor,
.destructor_cb = lv_menu_destructor,
.base_class = &lv_obj_class,
.width_def = (LV_DPI_DEF * 3) / 2,
.height_def = LV_DPI_DEF * 2,
.instance_size = sizeof(lv_menu_t),
.name = "menu",
};
const lv_obj_class_t lv_menu_page_class = {
.constructor_cb = lv_menu_page_constructor,
.destructor_cb = lv_menu_page_destructor,
.base_class = &lv_obj_class,
.width_def = LV_PCT(100),
.height_def = LV_SIZE_CONTENT,
.instance_size = sizeof(lv_menu_page_t),
.name = "menu-page",
};
const lv_obj_class_t lv_menu_cont_class = {
.constructor_cb = lv_menu_cont_constructor,
.base_class = &lv_obj_class,
.width_def = LV_PCT(100),
.height_def = LV_SIZE_CONTENT,
.name = "menu-cont",
};
const lv_obj_class_t lv_menu_section_class = {
.constructor_cb = lv_menu_section_constructor,
.base_class = &lv_obj_class,
.width_def = LV_PCT(100),
.height_def = LV_SIZE_CONTENT,
.name = "menu-section",
};
const lv_obj_class_t lv_menu_separator_class = {
.base_class = &lv_obj_class,
.width_def = LV_SIZE_CONTENT,
.height_def = LV_SIZE_CONTENT,
.name = "menu-separator",
};
const lv_obj_class_t lv_menu_sidebar_cont_class = {
.base_class = &lv_obj_class,
};
const lv_obj_class_t lv_menu_main_cont_class = {
.base_class = &lv_obj_class,
};
const lv_obj_class_t lv_menu_main_header_cont_class = {
.base_class = &lv_obj_class,
};
const lv_obj_class_t lv_menu_sidebar_header_cont_class = {
.base_class = &lv_obj_class,
};
static void lv_menu_refr(lv_obj_t * obj);
static void lv_menu_refr_sidebar_header_mode(lv_obj_t * obj);
static void lv_menu_refr_main_header_mode(lv_obj_t * obj);
static void lv_menu_load_page_event_cb(lv_event_t * e);
static void lv_menu_obj_delete_event_cb(lv_event_t * e);
static void lv_menu_back_event_cb(lv_event_t * e);
static void lv_menu_value_changed_event_cb(lv_event_t * e);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
bool lv_menu_item_back_button_is_root(lv_obj_t * menu, lv_obj_t * obj);
void lv_menu_clear_history(lv_obj_t * obj);
lv_obj_t * lv_menu_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;
}
lv_obj_t * lv_menu_page_create(lv_obj_t * parent, char const * const title)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(&lv_menu_page_class, parent);
lv_obj_class_init_obj(obj);
lv_menu_page_t * page = (lv_menu_page_t *)obj;
/* Initialise the object */
page->title = NULL;
page->static_title = false;
lv_menu_set_page_title(obj, title);
return obj;
}
lv_obj_t * lv_menu_cont_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(&lv_menu_cont_class, parent);
lv_obj_class_init_obj(obj);
return obj;
}
lv_obj_t * lv_menu_section_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(&lv_menu_section_class, parent);
lv_obj_class_init_obj(obj);
return obj;
}
lv_obj_t * lv_menu_separator_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(&lv_menu_separator_class, parent);
lv_obj_class_init_obj(obj);
return obj;
}
void lv_menu_refr(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
lv_ll_t * history_ll = &(menu->history_ll);
/* The current menu */
lv_menu_history_t * act_hist = _lv_ll_get_head(history_ll);
lv_obj_t * page = NULL;
if(act_hist != NULL) {
page = act_hist->page;
/* Delete the current item from the history */
_lv_ll_remove(history_ll, act_hist);
lv_free(act_hist);
menu->cur_depth--;
}
/* Set it */
lv_menu_set_page(obj, page);
}
/*=====================
* Setter functions
*====================*/
void lv_menu_set_page(lv_obj_t * obj, lv_obj_t * page)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
/* Hide previous page */
if(menu->main_page != NULL) {
lv_obj_set_parent(menu->main_page, menu->storage);
}
if(page != NULL) {
/* Add a new node */
lv_ll_t * history_ll = &(menu->history_ll);
lv_menu_history_t * new_node = _lv_ll_ins_head(history_ll);
LV_ASSERT_MALLOC(new_node);
new_node->page = page;
menu->cur_depth++;
/* Place page in main */
lv_obj_set_parent(page, menu->main);
}
else {
/* Empty page, clear history */
lv_menu_clear_history(obj);
}
menu->main_page = page;
/* If there is a selected tab, update checked state */
if(menu->selected_tab != NULL) {
if(menu->sidebar_page != NULL) {
lv_obj_add_state(menu->selected_tab, LV_STATE_CHECKED);
}
else {
lv_obj_remove_state(menu->selected_tab, LV_STATE_CHECKED);
}
}
/* Back btn management */
if(menu->sidebar_page != NULL) {
/* With sidebar enabled */
if(menu->sidebar_generated) {
if(menu->mode_root_back_btn == LV_MENU_ROOT_BACK_BUTTON_ENABLED) {
/* Root back btn is always shown if enabled*/
lv_obj_remove_flag(menu->sidebar_header_back_btn, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(menu->sidebar_header_back_btn, LV_OBJ_FLAG_CLICKABLE);
}
else {
lv_obj_add_flag(menu->sidebar_header_back_btn, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(menu->sidebar_header_back_btn, LV_OBJ_FLAG_CLICKABLE);
}
}
if(menu->cur_depth >= 2) {
lv_obj_remove_flag(menu->main_header_back_btn, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(menu->main_header_back_btn, LV_OBJ_FLAG_CLICKABLE);
}
else {
lv_obj_add_flag(menu->main_header_back_btn, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(menu->main_header_back_btn, LV_OBJ_FLAG_CLICKABLE);
}
}
else {
/* With sidebar disabled */
if(menu->cur_depth >= 2 || menu->mode_root_back_btn == LV_MENU_ROOT_BACK_BUTTON_ENABLED) {
lv_obj_remove_flag(menu->main_header_back_btn, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(menu->main_header_back_btn, LV_OBJ_FLAG_CLICKABLE);
}
else {
lv_obj_add_flag(menu->main_header_back_btn, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(menu->main_header_back_btn, LV_OBJ_FLAG_CLICKABLE);
}
}
lv_obj_send_event((lv_obj_t *)menu, LV_EVENT_VALUE_CHANGED, NULL);
lv_menu_refr_main_header_mode(obj);
}
void lv_menu_set_sidebar_page(lv_obj_t * obj, lv_obj_t * page)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
/* Sidebar management*/
if(page != NULL) {
/* Sidebar should be enabled */
if(!menu->sidebar_generated) {
/* Create sidebar */
lv_obj_t * sidebar_cont = lv_obj_class_create_obj(&lv_menu_sidebar_cont_class, obj);
lv_obj_class_init_obj(sidebar_cont);
lv_obj_move_to_index(sidebar_cont, 1);
lv_obj_set_size(sidebar_cont, LV_PCT(30), LV_PCT(100));
lv_obj_set_flex_flow(sidebar_cont, LV_FLEX_FLOW_COLUMN);
lv_obj_add_flag(sidebar_cont, LV_OBJ_FLAG_EVENT_BUBBLE);
lv_obj_remove_flag(sidebar_cont, LV_OBJ_FLAG_CLICKABLE);
menu->sidebar = sidebar_cont;
lv_obj_t * sidebar_header = lv_obj_class_create_obj(&lv_menu_sidebar_header_cont_class, sidebar_cont);
lv_obj_class_init_obj(sidebar_header);
lv_obj_set_size(sidebar_header, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(sidebar_header, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(sidebar_header, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_remove_flag(sidebar_header, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_flag(sidebar_header, LV_OBJ_FLAG_EVENT_BUBBLE);
menu->sidebar_header = sidebar_header;
lv_obj_t * sidebar_header_back_btn = lv_button_create(menu->sidebar_header);
lv_obj_add_event(sidebar_header_back_btn, lv_menu_back_event_cb, LV_EVENT_CLICKED, menu);
lv_obj_add_flag(sidebar_header_back_btn, LV_OBJ_FLAG_EVENT_BUBBLE);
lv_obj_set_flex_flow(sidebar_header_back_btn, LV_FLEX_FLOW_ROW);
menu->sidebar_header_back_btn = sidebar_header_back_btn;
lv_obj_t * sidebar_header_back_icon = lv_image_create(menu->sidebar_header_back_btn);
lv_image_set_src(sidebar_header_back_icon, LV_SYMBOL_LEFT);
lv_obj_t * sidebar_header_title = lv_label_create(menu->sidebar_header);
lv_obj_add_flag(sidebar_header_title, LV_OBJ_FLAG_HIDDEN);
menu->sidebar_header_title = sidebar_header_title;
menu->sidebar_generated = true;
}
lv_obj_set_parent(page, menu->sidebar);
lv_menu_refr_sidebar_header_mode(obj);
}
else {
/* Sidebar should be disabled */
if(menu->sidebar_generated) {
lv_obj_set_parent(menu->sidebar_page, menu->storage);
lv_obj_delete(menu->sidebar);
menu->sidebar_generated = false;
}
}
menu->sidebar_page = page;
lv_menu_refr(obj);
}
void lv_menu_set_mode_header(lv_obj_t * obj, lv_menu_mode_header_t mode_header)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
if(menu->mode_header != mode_header) {
menu->mode_header = mode_header;
lv_menu_refr_main_header_mode(obj);
if(menu->sidebar_generated) lv_menu_refr_sidebar_header_mode(obj);
}
}
void lv_menu_set_mode_root_back_button(lv_obj_t * obj, lv_menu_mode_root_back_button_t mode_root_back_btn)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
if(menu->mode_root_back_btn != mode_root_back_btn) {
menu->mode_root_back_btn = mode_root_back_btn;
lv_menu_refr(obj);
}
}
void lv_menu_set_load_page_event(lv_obj_t * menu, lv_obj_t * obj, lv_obj_t * page)
{
LV_ASSERT_OBJ(menu, MY_CLASS);
lv_obj_add_flag(obj, LV_OBJ_FLAG_CLICKABLE);
lv_obj_remove_flag(obj, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
/* Remove old event */
uint32_t i;
uint32_t event_cnt = lv_obj_get_event_count(obj);
for(i = 0; i < event_cnt; i++) {
lv_event_dsc_t * event_dsc = lv_obj_get_event_dsc(obj, i);
if(lv_event_dsc_get_cb(event_dsc) == lv_menu_load_page_event_cb) {
lv_obj_send_event(obj, LV_EVENT_DELETE, NULL);
lv_obj_remove_event(obj, i);
break;
}
}
lv_menu_load_page_event_data_t * event_data = lv_malloc(sizeof(lv_menu_load_page_event_data_t));
event_data->menu = menu;
event_data->page = page;
lv_obj_add_event(obj, lv_menu_load_page_event_cb, LV_EVENT_CLICKED, event_data);
lv_obj_add_event(obj, lv_menu_obj_delete_event_cb, LV_EVENT_DELETE, event_data);
}
void lv_menu_set_page_title(lv_obj_t * page_obj, char const * const title)
{
LV_LOG_INFO("begin");
lv_menu_page_t * page = (lv_menu_page_t *)page_obj;
/* Cleanup any previous set titles */
if((!page->static_title) && page->title) {
lv_free(page->title);
page->title = NULL;
}
if(title) {
page->static_title = false;
page->title = lv_strdup(title);
LV_ASSERT_MALLOC(page->title);
if(page->title == NULL) {
return;
}
}
else {
page->title = NULL;
page->static_title = false;
}
}
void lv_menu_set_page_title_static(lv_obj_t * page_obj, char const * const title)
{
LV_LOG_INFO("begin");
lv_menu_page_t * page = (lv_menu_page_t *)page_obj;
/* Cleanup any previous set titles */
if((!page->static_title) && page->title) {
lv_free(page->title);
page->title = NULL;
}
/* Set or clear the static title text */
if(title) {
page->title = (char *) title;
page->static_title = true;
}
else {
page->title = NULL;
page->static_title = false;
}
}
/*=====================
* Getter functions
*====================*/
lv_obj_t * lv_menu_get_cur_main_page(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
return menu->main_page;
}
lv_obj_t * lv_menu_get_cur_sidebar_page(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
return menu->sidebar_page;
}
lv_obj_t * lv_menu_get_main_header(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
return menu->main_header;
}
lv_obj_t * lv_menu_get_main_header_back_button(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
return menu->main_header_back_btn;
}
lv_obj_t * lv_menu_get_sidebar_header(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
return menu->sidebar_header;
}
lv_obj_t * lv_menu_get_sidebar_header_back_button(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
return menu->sidebar_header_back_btn;
}
bool lv_menu_back_button_is_root(lv_obj_t * menu, lv_obj_t * obj)
{
LV_ASSERT_OBJ(menu, MY_CLASS);
if(obj == ((lv_menu_t *)menu)->sidebar_header_back_btn) {
return true;
}
if(obj == ((lv_menu_t *)menu)->main_header_back_btn && ((lv_menu_t *)menu)->prev_depth <= 1) {
return true;
}
return false;
}
void lv_menu_clear_history(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
lv_ll_t * history_ll = &(menu->history_ll);
_lv_ll_clear(history_ll);
menu->cur_depth = 0;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_menu_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_obj_set_layout(obj, LV_LAYOUT_FLEX);
lv_obj_set_flex_flow(obj, LV_FLEX_FLOW_ROW);
lv_menu_t * menu = (lv_menu_t *)obj;
menu->mode_header = LV_MENU_HEADER_TOP_FIXED;
menu->mode_root_back_btn = LV_MENU_ROOT_BACK_BUTTON_DISABLED;
menu->cur_depth = 0;
menu->prev_depth = 0;
menu->sidebar_generated = false;
_lv_ll_init(&(menu->history_ll), sizeof(lv_menu_history_t));
menu->storage = lv_obj_create(obj);
lv_obj_add_flag(menu->storage, LV_OBJ_FLAG_HIDDEN);
menu->sidebar = NULL;
menu->sidebar_header = NULL;
menu->sidebar_header_back_btn = NULL;
menu->sidebar_header_title = NULL;
menu->sidebar_page = NULL;
lv_obj_t * main_cont = lv_obj_class_create_obj(&lv_menu_main_cont_class, obj);
lv_obj_class_init_obj(main_cont);
lv_obj_set_height(main_cont, LV_PCT(100));
lv_obj_set_flex_grow(main_cont, 1);
lv_obj_set_flex_flow(main_cont, LV_FLEX_FLOW_COLUMN);
lv_obj_add_flag(main_cont, LV_OBJ_FLAG_EVENT_BUBBLE);
lv_obj_remove_flag(main_cont, LV_OBJ_FLAG_CLICKABLE);
menu->main = main_cont;
lv_obj_t * main_header = lv_obj_class_create_obj(&lv_menu_main_header_cont_class, main_cont);
lv_obj_class_init_obj(main_header);
lv_obj_set_size(main_header, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(main_header, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(main_header, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_remove_flag(main_header, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_flag(main_header, LV_OBJ_FLAG_EVENT_BUBBLE);
menu->main_header = main_header;
/* Create the default simple back btn and title */
lv_obj_t * main_header_back_btn = lv_button_create(menu->main_header);
lv_obj_add_event(main_header_back_btn, lv_menu_back_event_cb, LV_EVENT_CLICKED, menu);
lv_obj_add_flag(main_header_back_btn, LV_OBJ_FLAG_EVENT_BUBBLE);
lv_obj_set_flex_flow(main_header_back_btn, LV_FLEX_FLOW_ROW);
menu->main_header_back_btn = main_header_back_btn;
lv_obj_t * main_header_back_icon = lv_image_create(menu->main_header_back_btn);
lv_image_set_src(main_header_back_icon, LV_SYMBOL_LEFT);
lv_obj_t * main_header_title = lv_label_create(menu->main_header);
lv_obj_add_flag(main_header_title, LV_OBJ_FLAG_HIDDEN);
menu->main_header_title = main_header_title;
menu->main_page = NULL;
menu->selected_tab = NULL;
lv_obj_add_event(obj, lv_menu_value_changed_event_cb, LV_EVENT_VALUE_CHANGED, menu);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_menu_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_menu_t * menu = (lv_menu_t *)obj;
lv_ll_t * history_ll = &(menu->history_ll);
_lv_ll_clear(history_ll);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_menu_page_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_menu_t * menu = (lv_menu_t *)lv_obj_get_parent(obj);
lv_obj_set_parent(obj, ((lv_menu_t *)menu)->storage);
lv_obj_set_flex_flow(obj, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(obj, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_add_flag(obj, LV_OBJ_FLAG_EVENT_BUBBLE);
}
static void lv_menu_page_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_menu_page_t * page = (lv_menu_page_t *)obj;
if((!page->static_title) && page->title != NULL) {
lv_free(page->title);
}
page->title = NULL;
page->static_title = false;
}
static void lv_menu_cont_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_obj_set_flex_flow(obj, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(obj, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_remove_flag(obj, LV_OBJ_FLAG_CLICKABLE);
}
static void lv_menu_section_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_obj_set_flex_flow(obj, LV_FLEX_FLOW_COLUMN);
lv_obj_remove_flag(obj, LV_OBJ_FLAG_CLICKABLE);
}
static void lv_menu_refr_sidebar_header_mode(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
if(menu->sidebar_header == NULL || menu->sidebar_page == NULL) return;
switch(menu->mode_header) {
case LV_MENU_HEADER_TOP_FIXED:
/* Content should fill the remaining space */
lv_obj_move_to_index(menu->sidebar_header, 0);
lv_obj_set_flex_grow(menu->sidebar_page, 1);
break;
case LV_MENU_HEADER_TOP_UNFIXED:
lv_obj_move_to_index(menu->sidebar_header, 0);
lv_obj_set_flex_grow(menu->sidebar_page, 0);
break;
case LV_MENU_HEADER_BOTTOM_FIXED:
lv_obj_move_to_index(menu->sidebar_header, 1);
lv_obj_set_flex_grow(menu->sidebar_page, 1);
break;
}
lv_obj_refr_size(menu->sidebar_header);
lv_obj_refr_size(menu->sidebar_page);
if(lv_obj_get_content_height(menu->sidebar_header) == 0) {
lv_obj_add_flag(menu->sidebar_header, LV_OBJ_FLAG_HIDDEN);
}
else {
lv_obj_remove_flag(menu->sidebar_header, LV_OBJ_FLAG_HIDDEN);
}
}
static void lv_menu_refr_main_header_mode(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_menu_t * menu = (lv_menu_t *)obj;
if(menu->main_header == NULL || menu->main_page == NULL) return;
switch(menu->mode_header) {
case LV_MENU_HEADER_TOP_FIXED:
/* Content should fill the remaining space */
lv_obj_move_to_index(menu->main_header, 0);
lv_obj_set_flex_grow(menu->main_page, 1);
break;
case LV_MENU_HEADER_TOP_UNFIXED:
lv_obj_move_to_index(menu->main_header, 0);
lv_obj_set_flex_grow(menu->main_page, 0);
break;
case LV_MENU_HEADER_BOTTOM_FIXED:
lv_obj_move_to_index(menu->main_header, 1);
lv_obj_set_flex_grow(menu->main_page, 1);
break;
}
lv_obj_refr_size(menu->main_header);
lv_obj_refr_size(menu->main_page);
lv_obj_update_layout(menu->main_header);
if(lv_obj_get_content_height(menu->main_header) == 0) {
lv_obj_add_flag(menu->main_header, LV_OBJ_FLAG_HIDDEN);
}
else {
lv_obj_remove_flag(menu->main_header, LV_OBJ_FLAG_HIDDEN);
}
}
static void lv_menu_load_page_event_cb(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
lv_menu_load_page_event_data_t * event_data = lv_event_get_user_data(e);
lv_menu_t * menu = (lv_menu_t *)(event_data->menu);
lv_obj_t * page = event_data->page;
if(menu->sidebar_page != NULL) {
/* Check if clicked obj is in the sidebar */
bool sidebar = false;
lv_obj_t * parent = obj;
while(parent) {
if(parent == (lv_obj_t *)menu) break;
if(parent == menu->sidebar) {
sidebar = true;
break;
}
parent = lv_obj_get_parent(parent);
}
if(sidebar) {
/* Clear checked state of previous obj */
if(menu->selected_tab != obj && menu->selected_tab != NULL) {
lv_obj_remove_state(menu->selected_tab, LV_STATE_CHECKED);
}
lv_menu_clear_history((lv_obj_t *)menu);
menu->selected_tab = obj;
}
}
lv_menu_set_page((lv_obj_t *)menu, page);
if(lv_group_get_default() != NULL && menu->sidebar_page == NULL) {
/* Sidebar is not supported for now*/
lv_group_focus_next(lv_group_get_default());
}
}
static void lv_menu_obj_delete_event_cb(lv_event_t * e)
{
lv_menu_load_page_event_data_t * event_data = lv_event_get_user_data(e);
lv_free(event_data);
}
static void lv_menu_back_event_cb(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
/* LV_EVENT_CLICKED */
if(code == LV_EVENT_CLICKED) {
lv_obj_t * obj = lv_event_get_target(e);
lv_menu_t * menu = (lv_menu_t *)lv_event_get_user_data(e);
if(!(obj == menu->main_header_back_btn || obj == menu->sidebar_header_back_btn)) return;
menu->prev_depth = menu->cur_depth; /* Save the previous value for user event handler */
if(lv_menu_back_button_is_root((lv_obj_t *)menu, obj)) return;
lv_ll_t * history_ll = &(menu->history_ll);
/* The current menu */
lv_menu_history_t * act_hist = _lv_ll_get_head(history_ll);
/* The previous menu */
lv_menu_history_t * prev_hist = _lv_ll_get_next(history_ll, act_hist);
if(prev_hist != NULL) {
/* Previous menu exists */
/* Delete the current item from the history */
_lv_ll_remove(history_ll, act_hist);
lv_free(act_hist);
menu->cur_depth--;
/* Create the previous menu.
* Remove it from the history because `lv_menu_set_page` will add it again */
_lv_ll_remove(history_ll, prev_hist);
menu->cur_depth--;
lv_menu_set_page(&(menu->obj), prev_hist->page);
lv_free(prev_hist);
}
}
}
static void lv_menu_value_changed_event_cb(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_user_data(e);
lv_menu_t * menu = (lv_menu_t *)obj;
lv_menu_page_t * main_page = (lv_menu_page_t *)lv_menu_get_cur_main_page(obj);
if(main_page != NULL && menu->main_header_title != NULL) {
if(main_page->title != NULL) {
lv_label_set_text(menu->main_header_title, main_page->title);
lv_obj_remove_flag(menu->main_header_title, LV_OBJ_FLAG_HIDDEN);
}
else {
lv_obj_add_flag(menu->main_header_title, LV_OBJ_FLAG_HIDDEN);
}
}
lv_menu_page_t * sidebar_page = (lv_menu_page_t *)lv_menu_get_cur_sidebar_page(obj);
if(sidebar_page != NULL && menu->sidebar_header_title != NULL) {
if(sidebar_page->title != NULL) {
lv_label_set_text(menu->sidebar_header_title, sidebar_page->title);
lv_obj_remove_flag(menu->sidebar_header_title, LV_OBJ_FLAG_HIDDEN);
}
else {
lv_obj_add_flag(menu->sidebar_header_title, LV_OBJ_FLAG_HIDDEN);
}
}
}
#endif /*LV_USE_MENU*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets | repos/zig_workbench/BaseLVGL/lib/lvgl/src/widgets/menu/lv_menu.h | /**
* @file lv_menu.h
*
*/
#ifndef LV_MENU_H
#define LV_MENU_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../core/lv_obj.h"
#if LV_USE_MENU
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
enum _lv_menu_mode_header_t {
LV_MENU_HEADER_TOP_FIXED, /* Header is positioned at the top */
LV_MENU_HEADER_TOP_UNFIXED, /* Header is positioned at the top and can be scrolled out of view*/
LV_MENU_HEADER_BOTTOM_FIXED /* Header is positioned at the bottom */
};
#ifdef DOXYGEN
typedef _lv_menu_mode_header_t lv_menu_mode_header_t;
#else
typedef uint8_t lv_menu_mode_header_t;
#endif /*DOXYGEN*/
enum _lv_menu_mode_root_back_button_t {
LV_MENU_ROOT_BACK_BUTTON_DISABLED,
LV_MENU_ROOT_BACK_BUTTON_ENABLED
};
#ifdef DOXYGEN
typedef _lv_menu_mode_root_back_button_t lv_menu_mode_root_back_button_t;
#else
typedef uint8_t lv_menu_mode_root_back_button_t;
#endif /*DOXYGEN*/
typedef struct /// @cond
/**
* Tells Doxygen to ignore a duplicate declaration
*/
lv_menu_load_page_event_data_t
/// @endcond
{
lv_obj_t * menu;
lv_obj_t * page;
} lv_menu_load_page_event_data_t ;
typedef struct {
lv_obj_t * page;
} lv_menu_history_t;
typedef struct {
lv_obj_t obj;
lv_obj_t * storage; /* a pointer to obj that is the parent of all pages not displayed */
lv_obj_t * main;
lv_obj_t * main_page;
lv_obj_t * main_header;
lv_obj_t *
main_header_back_btn; /* a pointer to obj that on click triggers back btn event handler, can be same as 'main_header' */
lv_obj_t * main_header_title;
lv_obj_t * sidebar;
lv_obj_t * sidebar_page;
lv_obj_t * sidebar_header;
lv_obj_t *
sidebar_header_back_btn; /* a pointer to obj that on click triggers back btn event handler, can be same as 'sidebar_header' */
lv_obj_t * sidebar_header_title;
lv_obj_t * selected_tab;
lv_ll_t history_ll;
uint8_t cur_depth;
uint8_t prev_depth;
uint8_t sidebar_generated : 1;
lv_menu_mode_header_t mode_header : 2;
lv_menu_mode_root_back_button_t mode_root_back_btn : 1;
} lv_menu_t;
typedef struct {
lv_obj_t obj;
char * title;
bool static_title;
} lv_menu_page_t;
extern const lv_obj_class_t lv_menu_class;
extern const lv_obj_class_t lv_menu_page_class;
extern const lv_obj_class_t lv_menu_cont_class;
extern const lv_obj_class_t lv_menu_section_class;
extern const lv_obj_class_t lv_menu_separator_class;
extern const lv_obj_class_t lv_menu_sidebar_cont_class;
extern const lv_obj_class_t lv_menu_main_cont_class;
extern const lv_obj_class_t lv_menu_sidebar_header_cont_class;
extern const lv_obj_class_t lv_menu_main_header_cont_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a menu object
* @param parent pointer to an object, it will be the parent of the new menu
* @return pointer to the created menu
*/
lv_obj_t * lv_menu_create(lv_obj_t * parent);
/**
* Create a menu page object
* @param parent pointer to menu object
* @param title pointer to text for title in header (NULL to not display title)
* @return pointer to the created menu page
*/
lv_obj_t * lv_menu_page_create(lv_obj_t * parent, char const * const title);
/**
* Create a menu cont object
* @param parent pointer to an object, it will be the parent of the new menu cont object
* @return pointer to the created menu cont
*/
lv_obj_t * lv_menu_cont_create(lv_obj_t * parent);
/**
* Create a menu section object
* @param parent pointer to an object, it will be the parent of the new menu section object
* @return pointer to the created menu section
*/
lv_obj_t * lv_menu_section_create(lv_obj_t * parent);
/**
* Create a menu separator object
* @param parent pointer to an object, it will be the parent of the new menu separator object
* @return pointer to the created menu separator
*/
lv_obj_t * lv_menu_separator_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set menu page to display in main
* @param obj pointer to the menu
* @param page pointer to the menu page to set (NULL to clear main and clear menu history)
*/
void lv_menu_set_page(lv_obj_t * obj, lv_obj_t * page);
/**
* Set menu page title
* @param page pointer to the menu page
* @param title pointer to text for title in header (NULL to not display title)
*/
void lv_menu_set_page_title(lv_obj_t * page, char const * const title);
/**
* Set menu page title with a static text. It will not be saved by the label so the 'text' variable
* has to be 'alive' while the page exists.
* @param page pointer to the menu page
* @param title pointer to text for title in header (NULL to not display title)
*/
void lv_menu_set_page_title_static(lv_obj_t * page, char const * const title);
/**
* Set menu page to display in sidebar
* @param obj pointer to the menu
* @param page pointer to the menu page to set (NULL to clear sidebar)
*/
void lv_menu_set_sidebar_page(lv_obj_t * obj, lv_obj_t * page);
/**
* Set the how the header should behave and its position
* @param obj pointer to a menu
* @param mode_header
*/
void lv_menu_set_mode_header(lv_obj_t * obj, lv_menu_mode_header_t mode_header);
/**
* Set whether back button should appear at root
* @param obj pointer to a menu
* @param mode_root_back_btn
*/
void lv_menu_set_mode_root_back_button(lv_obj_t * obj, lv_menu_mode_root_back_button_t mode_root_back_btn);
/**
* Add menu to the menu item
* @param menu pointer to the menu
* @param obj pointer to the obj
* @param page pointer to the page to load when obj is clicked
*/
void lv_menu_set_load_page_event(lv_obj_t * menu, lv_obj_t * obj, lv_obj_t * page);
/*=====================
* Getter functions
*====================*/
/**
* Get a pointer to menu page that is currently displayed in main
* @param obj pointer to the menu
* @return pointer to current page
*/
lv_obj_t * lv_menu_get_cur_main_page(lv_obj_t * obj);
/**
* Get a pointer to menu page that is currently displayed in sidebar
* @param obj pointer to the menu
* @return pointer to current page
*/
lv_obj_t * lv_menu_get_cur_sidebar_page(lv_obj_t * obj);
/**
* Get a pointer to main header obj
* @param obj pointer to the menu
* @return pointer to main header obj
*/
lv_obj_t * lv_menu_get_main_header(lv_obj_t * obj);
/**
* Get a pointer to main header back btn obj
* @param obj pointer to the menu
* @return pointer to main header back btn obj
*/
lv_obj_t * lv_menu_get_main_header_back_button(lv_obj_t * obj);
/**
* Get a pointer to sidebar header obj
* @param obj pointer to the menu
* @return pointer to sidebar header obj
*/
lv_obj_t * lv_menu_get_sidebar_header(lv_obj_t * obj);
/**
* Get a pointer to sidebar header obj
* @param obj pointer to the menu
* @return pointer to sidebar header back btn obj
*/
lv_obj_t * lv_menu_get_sidebar_header_back_button(lv_obj_t * obj);
/**
* Check if an obj is a root back btn
* @param menu pointer to the menu
* @param obj pointer to the back button
* @return true if it is a root back btn
*/
bool lv_menu_back_button_is_root(lv_obj_t * menu, lv_obj_t * obj);
/**
* Clear menu history
* @param obj pointer to the menu
*/
void lv_menu_clear_history(lv_obj_t * obj);
/**********************
* MACROS
**********************/
#endif /*LV_USE_MENU*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_MENU_H*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.