Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/outcome/doc/src | repos/outcome/doc/src/snippets/quick_status_code_from_enum.cpp | /* Example use of std::error implicit conversion
(C) 2024 Niall Douglas <http://www.nedproductions.biz/> (5 commits)
File Created: Sept 2018
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include "../../../include/outcome/experimental/status-code/include/status-code/quick_status_code_from_enum.hpp"
#include "../../../include/outcome/experimental/status_result.hpp"
#include "outcome/experimental/status-code/include/status-code/config.hpp"
//! [preamble]
// My custom enum type
enum class custom_failure
{
not_found,
bad_argument
};
// Tell `status_code` to stamp out a custom code domain for this enum type
SYSTEM_ERROR2_NAMESPACE_BEGIN
template <> struct quick_status_code_from_enum<custom_failure> : quick_status_code_from_enum_defaults<custom_failure>
{
// Text name of the enum
static constexpr const auto domain_name = "My custom failure";
// Unique UUID for the enum. PLEASE use https://www.random.org/cgi-bin/randbyte?nbytes=16&format=h
static constexpr const auto domain_uuid = "{be201f65-3962-dd0e-1266-a72e63776a42}";
// Map of each enum value to its text string, and list of semantically equivalent errc's
static const std::initializer_list<mapping> &value_mappings()
{
static const std::initializer_list<mapping> v = {
// Format is: { enum value, "string representation", { list of errc mappings ... } }
{custom_failure::not_found, "item not found", {errc::no_such_file_or_directory}}, //
{custom_failure::bad_argument, "invoked wrong", {errc::invalid_argument}}, //
};
return v;
}
// Completely optional definition of mixin for the status code synthesised from `Enum`. It can be omitted.
template <class Base> struct mixin : Base
{
using Base::Base;
constexpr int custom_method() const { return 42; }
};
};
SYSTEM_ERROR2_NAMESPACE_END
//! [preamble]
//! [implicit_construction]
// This is the status code generated for your custom enum type. It will implicitly construct from
// values of enum custom_failure.
using custom_failure_code = SYSTEM_ERROR2_NAMESPACE::quick_status_code_from_enum_code<custom_failure>;
namespace outcome_e = OUTCOME_V2_NAMESPACE::experimental;
// You don't usually need to use the status code type explicitly, because this "just works":
outcome_e::status_result<int> positive_only(int x)
{
if(x < 0)
{
// Outcome's result sees that status_code will implicitly construct from this enum,
// and it returns an errored result
return custom_failure::bad_argument;
}
return x;
}
// Semantic comparisons work
bool test(int x)
{
if(auto r = positive_only(x); !r)
{
if(r.error() == outcome_e::errc::invalid_argument)
{
std::cerr << "Positive numbers only!" << std::endl;
return false;
}
}
return true;
}
//! [implicit_construction]
int main(void)
{
if(!test(0))
abort();
if(test(-1))
abort();
return 0;
}
|
0 | repos/outcome/doc/src | repos/outcome/doc/src/snippets/void_terminate.cpp | /* Example of Outcome used with void
(C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (1 commit)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include "../../../include/outcome.hpp"
#include <iostream>
int main()
{
using namespace OUTCOME_V2_NAMESPACE;
//! [void_terminate]
struct udt
{
int a{0};
explicit udt(int _a)
: a(_a)
{
}
udt() = default;
int operator*() const { return a; }
};
result<udt, void> res(in_place_type<void>);
// What happens here? What exception type is thrown?
try
{
std::cout << *res.value() << std::endl;
}
catch(const std::exception &e)
{
std::cerr << "Exception thrown was " << e.what() << std::endl;
}
//! [void_terminate]
return 0;
}
|
0 | repos/outcome/doc/src | repos/outcome/doc/src/snippets/intro_c_example.cpp | /* Example of Outcome
(C) 2024 Niall Douglas <http://www.nedproductions.biz/>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include "../../../include/outcome/experimental/result.h"
#include <stdio.h>
void use_string(const char *foo)
{
(void) foo;
}
//! [signature]
CXX_DECLARE_RESULT_SYSTEM(result_string, const char *)
CXX_RESULT_SYSTEM(result_string) data_from_file(const char *path);
//! [signature]
int main()
{
//! [inspect]
CXX_RESULT_SYSTEM(result_string) rslt = data_from_file("config.cfg");
if(CXX_RESULT_HAS_VALUE(rslt))
use_string(rslt.value); // returns string
else
fprintf(stderr, "%s\n", outcome_status_code_message(&rslt.error));
//! [inspect]
}
//! [implementation]
CXX_DECLARE_RESULT_SYSTEM(result_int, int)
CXX_RESULT_SYSTEM(result_int) process(const char *content);
CXX_RESULT_SYSTEM(result_int) int_from_file(const char *path)
{
CXX_RESULT_SYSTEM_TRY(const char *str, result_int, /* cleanup on fail */, data_from_file(path));
// if control gets here data_from_file() has succeeded
return process(str); // decltype(str) == string
}
//! [implementation]
CXX_RESULT_SYSTEM(result_int) process(const char *foo)
{
(void) foo;
return outcome_make_result_system_result_int_success(1);
}
CXX_RESULT_SYSTEM(result_string) data_from_file(const char *path)
{
(void) path;
return outcome_make_result_system_result_string_success("");
}
|
0 | repos/outcome/doc/src | repos/outcome/doc/src/snippets/experimental_status_code.cpp | /* Example use of std::error implicit conversion
(C) 2018-2019 Niall Douglas <http://www.nedproductions.biz/> (5 commits)
File Created: Sept 2018
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h> // for sprintf
#if !defined(__GNUC__) || __GNUC__ > 6 // GCC 6 chokes on this
#include "../../../include/outcome/experimental/status_result.hpp"
#include "../../../include/outcome/experimental/status-code/include/status-code/nested_status_code.hpp"
/* Original note to WG21:
This code is to prove that proposed P1028 `std::error` need not be more
than two CPU registers in size, yet it can still transport arbitrary
payload.
We firstly will define a custom code domain for a `file_io_error` code whose
value type carries __FILE__ and __LINE__ (i.e. `source_location`) in
addition to the cause of the error. This is what one would expect end
users to do in order to define a specialised failure type local to
a specific piece of code, or library. In our case, `file_io_error`
will be lightweight and deterministic by being trivially copyable.
We secondly will tell the type system that an implicit conversion
between `file_io_error` and `error` exists via `make_status_code_ptr()`.
This bundles the `file_io_error` instance into dynamically allocated
memory, and returns an `error` instance referring to that.
Thus if under P0709 a function with `throws(file_io_error)` is called
by a function with merely `throws(std::error)`, a `std::error` can be
**implicitly** constructed by the compiler from the `file_io_error`. I
prove this in code below (see end).
*/
/********************** Example boilerplate begins ***********************/
//! [preamble]
namespace outcome_e = OUTCOME_V2_NAMESPACE::experimental;
// To define a `file_io_error` which participates in the P1028 world
// of `std::error`, we must first declare, then define, a custom code
// domain which extends `posix_code` (the std error coding for POSIX
// failures). The following is fairly standard boilerplate for defining
// a custom code domain. It is analogous to defining a custom `std::error_category`.
class _file_io_error_domain;
// We define `file_io_error` to be the status code whose domain is `_file_io_error_domain`.
using file_io_error = outcome_e::status_code<_file_io_error_domain>;
// Now we define `_file_io_error_domain`.
class _file_io_error_domain : public outcome_e::posix_code::domain_type
{
using _base = typename outcome_e::posix_code::domain_type;
//! [preamble]
//! [value_type]
public:
// This is the value type for `file_io_error`. We add line number and source file path.
struct value_type
{
typename outcome_e::posix_code::value_type errcode; // from POSIX, as we inherit from _posix_code_domain
// Our additional payload
int lineno; // from __LINE__
const char *file; // from __FILE__
// Could also place a backtrace of void *[16] here ...
};
//! [value_type]
//! [constructor]
// unique id must be from a hard random number source
// Use https://www.random.org/cgi-bin/randbyte?nbytes=8&format=h to get a hard random 64 bit id.
// Do NOT make up your own value. Do NOT use zero.
constexpr explicit _file_io_error_domain(typename _base::unique_id_type id = 0x230f170194fcc6c7) noexcept : _base(id) {}
static inline constexpr const _file_io_error_domain &get();
//! [constructor]
//! [string_ref]
// Return the name of our custom code domain
virtual _base::string_ref name() const noexcept override final // NOLINT
{
static string_ref v("file i/o error domain");
return v; // NOLINT
}
//! [string_ref]
//! [message]
// Return a string describing a specific code. We will return the
// string returned by our POSIX code base domain, with the source
// file and line number appended
virtual _base::string_ref _do_message(const outcome_e::status_code<void> &code) const noexcept override final // NOLINT
{
assert(code.domain() == *this);
// Fetch message from base domain (POSIX)
auto msg = _base::_do_message(code);
const auto &c1 = static_cast<const file_io_error &>(code); // NOLINT
const value_type &v = c1.value();
// Append my source file and line number
if(v.file == nullptr)
{
return msg;
}
size_t length = strlen(v.file) + 16 + msg.size();
auto *p = static_cast<char *>(malloc(length)); // NOLINT
if(p == nullptr)
{
return _base::string_ref("failed to get message from system");
}
sprintf(p, "%s (%s:%d)", msg.data(), v.file, v.lineno);
// Return as atomically reference counted string
return _base::atomic_refcounted_string_ref(p, length);
}
};
//! [message]
//! [constexpr_source]
// 100% constexpr instantiation
constexpr _file_io_error_domain file_io_error_domain;
inline constexpr const _file_io_error_domain &_file_io_error_domain::get()
{
return file_io_error_domain;
}
//! [constexpr_source]
//! [implicit_conversion]
// Now tell `error` how it can implicitly construct from `file_io_error`.
// This is done by us defining a free function called `make_status_code()`
// which is discovered using ADL. `error` is an alias to the refinement
// `status_code<erased<intptr_t>>` which is a status code whose value type
// has been erased into an `intptr_t`. `status_code<erased<intptr_t>>`
// (i.e. `error`) are move bitcopying (P1029) i.e. they are move-only
// types whose move operation is defined to leave the source in the same
// representation as a default constructed instance, and for whose
// non-trivial destructor when called upon a default constructed instance
// is guaranteed to do nothing.
inline outcome_e::system_code make_status_code(file_io_error v)
{
// `make_nested_status_code()` dynamically allocates memory to store an
// instance of `file_io_error`, then returns a status code whose domain
// specifies that its value type is a pointer to `file_io_error`. The
// domain is a templated instance which indirects all observers of the
// status code to the pointed-to status code.
//
// Note that the status code returned's value type is a pointer, which
// by definition fits into `intptr_t` and is trivially copyable.
// Therefore `system_code` (which is also a type alias to
// `status_code<erased<intptr_t>>`) is happy to implicitly construct
// from the status code returned by `make_nested_status_code()`.
return make_nested_status_code(std::move(v));
}
//! [implicit_conversion]
/********************** Proof it works begins ***********************/
#include <memory>
#include <utility>
struct file_deleter
{
void operator()(FILE *h) const
{
if(h != nullptr)
::fclose(h);
}
};
using file_handle = std::unique_ptr<FILE, file_deleter>;
//! [typedef]
template <class T, class E = outcome_e::error>
using result = //
outcome_e::status_result<T, E, outcome_e::policy::default_status_result_policy<T, E>>;
//! [typedef]
//! [open_file]
result<file_handle, file_io_error> open_file(const char *path) // models throws(file_io_error)
{
file_handle ret(::fopen(path, "r"));
if(ret)
return ret;
return file_io_error({errno, __LINE__, __FILE__});
}
result<void> open_resource() // models throws(std::error)
{
for(;;)
{
result<file_handle, file_io_error> r = open_file("some file");
if(r)
break;
file_io_error e = r.error();
if(e != outcome_e::errc::resource_unavailable_try_again)
{
// NOTE this implicitly converts from `file_io_error` to `error` via the
// `make_status_code()` free function customisation point defined above.
return e;
}
}
// success continues here ...
return outcome_e::success();
}
int main(void)
{
result<void> r = open_resource();
if(r)
printf("Success!\n");
else
{
auto e = std::move(r).error();
// A quick demonstration that the indirection works as indicated
printf("Returned error has a code domain of '%s', a message of '%s'\n", e.domain().name().c_str(), e.message().c_str());
printf("\nAnd semantically comparing it to 'errc::no_such_file_or_directory' = %d\n", e == outcome_e::errc::no_such_file_or_directory);
}
}
//! [open_file]
#else
int main(void)
{
return 0;
}
#endif
|
0 | repos/outcome/doc/src | repos/outcome/doc/src/snippets/constructors.cpp | /* Example of Outcome used with constructors
(C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (5 commits)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NONSTDC_NO_WARNINGS
#include <fcntl.h>
#include <io.h>
#else
#define file_handle linux_file_handle
#include <fcntl.h>
#include <unistd.h>
#undef file_handle
#endif
#include <cstring> // for strerror
#include <sys/stat.h>
#include <sys/types.h>
#include "../../../include/outcome.hpp"
#if __has_include(<filesystem>) && (__cplusplus >= 201700 || _HAS_CXX17)
#include <filesystem>
namespace filesystem = std::filesystem;
#else
#include <experimental/filesystem>
namespace filesystem = std::experimental::filesystem;
#endif
namespace outcome = OUTCOME_V2_NAMESPACE;
//! [file_handle]
class file_handle
{
int _fd{-1}; // file descriptor
struct stat _stat
{
0
}; // stat of the fd at open
// Phase 1 private constexpr constructor
constexpr file_handle() {}
public:
using path_type = filesystem::path;
//! The behaviour of the handle: does it read, read and write, or atomic append?
enum class mode : unsigned char // bit 0 set means writable
{
unchanged = 0,
none = 2, //!< No ability to read or write anything, but can synchronise (SYNCHRONIZE or 0)
attr_read = 4, //!< Ability to read attributes (FILE_READ_ATTRIBUTES|SYNCHRONIZE or O_RDONLY)
attr_write = 5, //!< Ability to read and write attributes (FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES|SYNCHRONIZE or O_RDONLY)
read = 6, //!< Ability to read (READ_CONTROL|FILE_READ_DATA|FILE_READ_ATTRIBUTES|FILE_READ_EA|SYNCHRONISE or O_RDONLY)
write = 7, //!< Ability to read and write (READ_CONTROL|FILE_READ_DATA|FILE_READ_ATTRIBUTES|FILE_READ_EA|FILE_WRITE_DATA|FILE_WRITE_ATTRIBUTES|FILE_WRITE_EA|FILE_APPEND_DATA|SYNCHRONISE or O_RDWR)
append = 9 //!< All mainstream OSs and CIFS guarantee this is atomic with respect to all other appenders (FILE_APPEND_DATA|SYNCHRONISE or O_APPEND)
};
// Moves but not copies permitted
file_handle(const file_handle &) = delete;
file_handle(file_handle &&o) noexcept : _fd(o._fd) { o._fd = -1; }
file_handle &operator=(const file_handle &) = delete;
file_handle &operator=(file_handle &&o) noexcept
{
this->~file_handle();
new(this) file_handle(std::move(o));
return *this;
}
// Destruction closes the handle
~file_handle()
{
if(_fd != -1)
{
if(-1 == ::close(_fd))
{
int e = errno;
std::cerr << "FATAL: Closing the fd during destruction failed due to " << strerror(e) << std::endl;
std::terminate();
}
_fd = -1;
}
}
// Phase 2 static member constructor function, which cannot throw
static inline outcome::result<file_handle> file(path_type path, mode mode = mode::read) noexcept;
};
//! [file_handle]
//! [file]
// Phase 2 static member constructor function, which cannot throw
inline outcome::result<file_handle> file_handle::file(file_handle::path_type path, file_handle::mode mode) noexcept
{
// Perform phase 1 of object construction
file_handle ret;
// Perform phase 2 of object construction
int flags = 0;
switch(mode)
{
case mode::attr_read:
case mode::read:
flags = O_RDONLY;
break;
case mode::attr_write:
case mode::write:
flags = O_RDWR;
break;
case mode::append:
flags = O_APPEND;
break;
default:
return std::errc::invalid_argument;
}
ret._fd = ::open(path.u8string().c_str(), flags);
if(-1 == ret._fd)
{
// Note that if we bail out here, ~file_handle() will correctly not call ::close()
return {errno, std::system_category()};
}
if(-1 == ::fstat(ret._fd, &ret._stat))
{
// Note that if we bail out here, ~file_handle() will correctly call ::close()
return {errno, std::system_category()};
}
// Returning ret directly is an area full of compiler specific behaviour quirks,
// so be explicit by wrapping into an initialiser list with embedded move.
return {std::move(ret)};
}
//! [file]
//! [construct-declaration]
template <class T> struct make
{
outcome::result<T> operator()() const noexcept
{ //
static_assert(!std::is_same<T, T>::value, //
"make<T>() was not specialised for the type T supplied");
}
};
//! [construct-declaration]
//! [construct-specialisation]
template <> struct make<file_handle>
{
file_handle::path_type _path;
file_handle::mode _mode{file_handle::mode::read};
// Any other args, default initialised if necessary, follow here ...
outcome::result<file_handle> operator()() const noexcept //
{
return file_handle::file(std::move(_path));
}
};
//! [construct-specialisation]
int main()
{
//! [static-use]
outcome::result<file_handle> fh1 = file_handle::file("hello" /*, file_handle::mode::read */);
if(!fh1)
{
std::cerr << "Opening file 'hello' failed with " << fh1.error().message() << std::endl;
}
//! [static-use]
//! [construct-use]
outcome::result<file_handle> fh2 = make<file_handle>{"hello" /*, file_handle::mode::read */}();
if(!fh2)
{
std::cerr << "Opening file 'hello' failed with " << fh2.error().message() << std::endl;
}
//! [construct-use]
return 0;
} |
0 | repos/outcome/doc/src | repos/outcome/doc/src/snippets/cpp_api.cpp | /* Example of Outcome used with C APIs
(C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (2 commits)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include <cstring> // for memcpy
#include <string>
#include "../../../include/outcome/experimental/status-code/include/status-code/system_code_from_exception.hpp"
#include "../../../include/outcome/experimental/status_result.hpp"
//! [function]
namespace outcome_e = OUTCOME_V2_NAMESPACE::experimental;
// Fill the supplied buffer with the integer v converted to a string,
// returning length of string minus null terminator
outcome_e::status_result<size_t> to_string(char *buffer, size_t bufferlen, int v) noexcept
{
try
{
// Could throw an exception!
std::string temp(std::to_string(v));
// Will this string exceed the supplied buffer?
if(temp.size() + 1 > bufferlen)
return outcome_e::errc::no_buffer_space;
// Copy the string into the supplied buffer, and return length of string
memcpy(buffer, temp.data(), temp.size() + 1);
return temp.size();
}
catch(...)
{
// This is the <system_error2> analogue of Standard Outcome's
// error_from_exception() utility function. It consumes an exception
// ptr (defaulted to current exception), and tries to match it to a
// standard C++ library exception type, returning a system_code
// with an appropriate code domain (generic_code, posix_code,
// win32_code).
//
// Note that using this function requires including
// <outcome/experimental/status-code/include/system_code_from_exception.hpp>
// It is NOT included by Experimental Outcome by default.
return outcome_e::system_code_from_exception();
}
}
//! [function]
int main()
{
return 0;
}
|
0 | repos/outcome/doc/src | repos/outcome/doc/src/snippets/c_api2.cpp | /* Example of Outcome used with C APIs
(C) 2024 Niall Douglas <http://www.nedproductions.biz/> (4 commits)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
// This header in Experimental Outcome is pure C, it provides a suite of C helper macros
#include "../../../include/outcome/experimental/result.h"
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
//! [preamble]
// Declare to C a Result with a happy value of intptr_t
CXX_DECLARE_RESULT_SYSTEM(result_int, intptr_t)
// Save oneself typing out CXX_RESULT_SYSTEM(result_int) all the time
typedef CXX_RESULT_SYSTEM(result_int) result;
// Our custom C enum
enum c_enum
{
c_enum_not_found,
c_enum_bad_argument
};
// Make a custom status code domain for this C enum
CXX_DECLARE_RESULT_SYSTEM_FROM_ENUM(result_int, // The C Result type declared above
c_enum, // The C enum we wish to wrap
"{74ceb994-7622-3a21-07f0-b016aa705585}", // Unique UUID for this domain
// Mappings of C enum values to textual description and semantic equivalances to generic codes
{c_enum::c_enum_not_found, "item not found", {errc::no_such_file_or_directory}},
{c_enum::c_enum_bad_argument, "invoked wrong", {errc::invalid_argument}})
// Make helper macros
#define SUCCESS(v) CXX_MAKE_RESULT_SYSTEM_SUCCESS(result_int, (v))
#define FAILURE(v) CXX_MAKE_RESULT_SYSTEM_FROM_ENUM(result_int, c_enum, (v))
//! [preamble]
//! [using]
result positive_only(int x)
{
if(x < 0)
{
return FAILURE(c_enum_bad_argument);
}
return SUCCESS(x);
}
bool test(int x)
{
result r = positive_only(x);
if(CXX_RESULT_HAS_ERROR(r))
{
if(outcome_status_code_equal_generic(&r.error, EINVAL))
{
fprintf(stderr, "Positive numbers only!\n");
return false;
}
}
return true;
}
//! [using]
//! [try]
result test2(int x)
{
CXX_RESULT_SYSTEM_TRY(int v, // what to set to value if successful
fprintf(stderr, "Positive numbers only!\n"), // what cleanup to run if unsuccessful
positive_only(x));
return SUCCESS(v + 1);
}
//! [try]
int main(void)
{
if(!test(0))
abort();
if(test(-1))
abort();
return 0;
}
|
0 | repos/outcome/doc/src | repos/outcome/doc/src/snippets/error_code_enums1.cpp | /* Example of Outcome used with error code enums
(C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits) and Andrzej Krzemienski <[email protected]> (1 commit)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include "../../../include/outcome.hpp"
#include <iostream>
int main()
{
using namespace OUTCOME_V2_NAMESPACE;
//! [error_code_enums]
struct udt
{
int a{0};
explicit udt(int _a)
: a(_a)
{
}
udt() = default;
int operator*() const { return a; }
};
enum class err
{
success, // 0 should not represent an error
failure1, // (for rationale, see tutorial on error codes)
failure2
};
result<udt, err, policy::terminate> res(err::failure1);
// What happens here? What exception type is thrown?
try
{
std::cout << *res.value() << std::endl;
}
catch(const std::exception &e)
{
std::cerr << "Exception thrown was " << e.what() << std::endl;
}
//! [error_code_enums]
return 0;
}
|
0 | repos/outcome/doc/src | repos/outcome/doc/src/snippets/intro_example.cpp | /* Example of Outcome
(C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (4 commits), Andrzej Krzemienski <[email protected]> (3 commits), akrzemi1 <[email protected]> (1 commit) and Andrzej Krzemieński <[email protected]> (1 commit)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include "../../../include/outcome.hpp"
#include <string>
using std::string;
namespace outcome = OUTCOME_V2_NAMESPACE;
struct string_view
{
string_view(const char*) {}
operator string() { return {}; }
};
struct LibError : std::runtime_error
{
explicit LibError(std::error_code, string_view s) : std::runtime_error(s) {}
};
void use_string(string) {}
//! [signature]
outcome::result<string> data_from_file(string_view path) noexcept;
//! [signature]
int main() {
//! [inspect]
if (outcome::result<string> rslt = data_from_file("config.cfg"))
use_string(rslt.value()); // returns string
else
throw LibError{rslt.error(), "config.cfg"}; // returns error_code
//! [inspect]
}
//! [implementation]
outcome::result<int> process(const string& content) noexcept;
outcome::result<int> int_from_file(string_view path) noexcept
{
OUTCOME_TRY(auto str, data_from_file(path));
// if control gets here data_from_file() has succeeded
return process(str); // decltype(str) == string
}
//! [implementation]
outcome::result<int> process(const string&) noexcept
{
return outcome::success(1);
}
outcome::result<string> data_from_file(string_view) noexcept
{
return outcome::success("1");
}
|
0 | repos/outcome/doc/src | repos/outcome/doc/src/snippets/c_api.c | /* Example of Outcome used with C APIs
(C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (4 commits)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#define _CRT_SECURE_NO_WARNINGS 1
#include <errno.h>
#include <stdio.h>
#include <string.h> // for strerror
// This header in Experimental Outcome is pure C, it provides a suite of C helper macros
#include "../../../include/outcome/experimental/result.h"
//! [preamble]
// Declare our C++ function's returning result type. Only needs to be done once.
// This declares an `status_result<size_t, system_code>` which is an alias to
// `basic_result<size_t, status_code<erased<intptr_t>>>`.
//
// The first parameter is some unique identifier for this type which will be used
// whenever we reference this type in the future.
CXX_DECLARE_RESULT_SYSTEM(to_string_rettype, size_t)
// Tell C about our extern C++ function `to_string()`
extern CXX_RESULT_SYSTEM(to_string_rettype) _Z9to_stringPcmi(char *buffer, size_t bufferlen, int v);
//! [preamble]
//! [example]
void print(int v)
{
char buffer[4];
CXX_RESULT_SYSTEM(to_string_rettype) res;
res = _Z9to_stringPcmi(buffer, sizeof(buffer), v);
if(CXX_RESULT_HAS_VALUE(res))
{
printf("to_string(%d) fills buffer with '%s' of %zu characters\n", v, buffer, res.value);
return;
}
// Is the error returned in the POSIX domain and thus an errno?
if(CXX_RESULT_ERROR_IS_ERRNO(res))
{
fprintf(stderr, "to_string(%d) failed with error code %d (%s)\n", v, (int) res.error.value, strerror((int) res.error.value));
return;
}
fprintf(stderr, "to_string(%d) failed with unknown error code %lld\n", v, (long long) res.error.value);
}
int main(void)
{
print(9);
print(99);
print(999);
print(9999);
return 0;
}
//! [example]
extern CXX_RESULT_SYSTEM(to_string_rettype) _Z9to_stringPcmi(char *buffer, size_t bufferlen, int v)
{
// Fake a C++ function so it'll compile and run
CXX_RESULT_SYSTEM(to_string_rettype) ret;
memset(&ret, 0, sizeof(ret));
char temp[256];
sprintf(temp, "%d", v);
size_t len = strlen(temp);
if(len > bufferlen - 1)
{
ret.flags |= 18U;
ret.error.value = ENOBUFS;
return ret;
}
memcpy(buffer, temp, len + 1);
ret.flags |= 1U;
ret.value = len;
return ret;
} |
0 | repos/outcome/doc/src | repos/outcome/doc/src/snippets/error_code_registration.cpp | /* Documentation snippet
(C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits), Luke Peterson <[email protected]> (2 commits), Andrzej Krzemienski <[email protected]> (2 commits) and Andrzej Krzemieński <[email protected]> (1 commit)
File Created: Mar 2017
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
//! [error_code_registration]
#include <iostream>
#include <string> // for string printing
#include <system_error> // bring in std::error_code et al
// This is the custom error code enum
enum class ConversionErrc
{
Success = 0, // 0 should not represent an error
EmptyString = 1,
IllegalChar = 2,
TooLong = 3,
};
namespace std
{
// Tell the C++ 11 STL metaprogramming that enum ConversionErrc
// is registered with the standard error code system
template <> struct is_error_code_enum<ConversionErrc> : true_type
{
};
}
namespace detail
{
// Define a custom error code category derived from std::error_category
class ConversionErrc_category : public std::error_category
{
public:
// Return a short descriptive name for the category
virtual const char *name() const noexcept override final { return "ConversionError"; }
// Return what each enum means in text
virtual std::string message(int c) const override final
{
switch (static_cast<ConversionErrc>(c))
{
case ConversionErrc::Success:
return "conversion successful";
case ConversionErrc::EmptyString:
return "converting empty string";
case ConversionErrc::IllegalChar:
return "got non-digit char when converting to a number";
case ConversionErrc::TooLong:
return "the number would not fit into memory";
default:
return "unknown";
}
}
// OPTIONAL: Allow generic error conditions to be compared to me
virtual std::error_condition default_error_condition(int c) const noexcept override final
{
switch (static_cast<ConversionErrc>(c))
{
case ConversionErrc::EmptyString:
return make_error_condition(std::errc::invalid_argument);
case ConversionErrc::IllegalChar:
return make_error_condition(std::errc::invalid_argument);
case ConversionErrc::TooLong:
return make_error_condition(std::errc::result_out_of_range);
default:
// I have no mapping for this code
return std::error_condition(c, *this);
}
}
};
}
// Define the linkage for this function to be used by external code.
// This would be the usual __declspec(dllexport) or __declspec(dllimport)
// if we were in a Windows DLL etc. But for this example use a global
// instance but with inline linkage so multiple definitions do not collide.
#define THIS_MODULE_API_DECL extern inline
// Declare a global function returning a static instance of the custom category
THIS_MODULE_API_DECL const detail::ConversionErrc_category &ConversionErrc_category()
{
static detail::ConversionErrc_category c;
return c;
}
// Overload the global make_error_code() free function with our
// custom enum. It will be found via ADL by the compiler if needed.
inline std::error_code make_error_code(ConversionErrc e)
{
return {static_cast<int>(e), ConversionErrc_category()};
}
int main(void)
{
// Note that we can now supply ConversionErrc directly to error_code
std::error_code ec = ConversionErrc::IllegalChar;
std::cout << "ConversionErrc::IllegalChar is printed by std::error_code as "
<< ec << " with explanatory message " << ec.message() << std::endl;
// We can compare ConversionErrc containing error codes to generic conditions
std::cout << "ec is equivalent to std::errc::invalid_argument = "
<< (ec == std::errc::invalid_argument) << std::endl;
std::cout << "ec is equivalent to std::errc::result_out_of_range = "
<< (ec == std::errc::result_out_of_range) << std::endl;
return 0;
}
//! [error_code_registration]
|
0 | repos/outcome/doc/src/snippets | repos/outcome/doc/src/snippets/boost-only/asio_integration.cpp | /* Example of Outcome
(C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include <boost/asio/async_result.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/experimental.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/outcome.hpp>
#include <vector>
namespace asio = boost::asio;
namespace outcome = boost::outcome_v2;
using byte = char;
using boost::system::error_code;
void old(asio::ip::tcp::socket skt)
{
//! [old-use-case]
// Dynamically allocate a buffer to read into. This must be move-only
// so it can be attached to the completion handler, hence the unique_ptr.
auto buffer = std::make_unique<std::vector<byte>>(1024);
// Begin an asynchronous socket read, upon completion invoke
// the lambda function specified
skt.async_read_some(asio::buffer(buffer->data(), buffer->size()),
// Retain lifetime of the i/o buffer until completion
[buffer = std::move(buffer)](const error_code &ec, size_t bytes) {
// Handle the buffer read
if(ec)
{
std::cerr << "Buffer read failed with " << ec << std::endl;
return;
}
std::cout << "Read " << bytes << " bytes into buffer" << std::endl;
// buffer will be dynamically freed now
});
//! [old-use-case]
}
asio::experimental::awaitable<void> new_(asio::ip::tcp::socket skt)
{
//! [new-use-case]
// As coroutines suspend the calling thread whilst an asynchronous
// operation executes, we can use stack allocation instead of dynamic
// allocation
char buffer[1024];
// Get an ASIO completion token for the current coroutine (requires
// Coroutines TS)
asio::experimental::await_token token = //
co_await asio::experimental::this_coro::token();
// Asynchronously read data, suspending this coroutine until completion,
// returning the bytes of the data read into the result.
try
{
size_t bytesread = //
co_await skt.async_read_some(asio::buffer(buffer), token);
std::cout << "Read " << bytesread << " bytes into buffer" << std::endl;
}
catch(const std::system_error &e)
{
std::cerr << "Buffer read failed with " << e.what() << std::endl;
}
//! [new-use-case]
}
//! [as_result]
namespace detail
{
// Type sugar for wrapping an external completion token
template <class CompletionToken> struct as_result_t
{
CompletionToken token;
};
} // namespace detail
// Factory function for wrapping a third party completion token with
// our type sugar
template <class CompletionToken> //
inline auto as_result(CompletionToken &&token)
{
return detail::as_result_t<std::decay_t<CompletionToken>>{std::forward<CompletionToken>(token)};
};
//! [as_result]
//! [async_result1]
// Tell ASIO about a new kind of completion token, the kind returned
// from our as_result() factory function. This implementation is
// for functions with handlers void(error_code, T) only.
template <class CompletionToken, class T> //
struct asio::async_result<detail::as_result_t<CompletionToken>, //
void(error_code, T)> //
// NOTE we subclass for an async result taking an outcome::result
// as its completion handler. We will mangle the void(error_code, T)
// completion handler into this completion handler below.
: public asio::async_result<CompletionToken, void(outcome::result<T, error_code>)>
{
// The result type we shall return
using result_type = outcome::result<T, error_code>;
using _base = asio::async_result<CompletionToken, void(result_type)>;
// The awaitable type to be returned by the initiating function,
// the co_await of which will yield a result_type
using return_type = typename _base::return_type;
// Get what would be the completion handler for the async_result
// whose completion handler is void(result_type)
using result_type_completion_handler_type = //
typename _base::completion_handler_type;
//! [async_result1]
//! [async_result2]
// Wrap that completion handler with void(error_code, T) converting
// handler
struct completion_handler_type
{
// Pass through unwrapped completion token
template <class U>
completion_handler_type(::detail::as_result_t<U> &&ch)
: _handler(std::forward<U>(ch.token))
{
}
// Our completion handler spec
void operator()(error_code ec, T v)
{
// Call the underlying completion handler, whose
// completion function is void(result_type)
if(ec)
{
// Complete with a failed result
_handler(result_type(outcome::failure(ec)));
return;
}
// Complete with a successful result
_handler(result_type(outcome::success(v)));
}
result_type_completion_handler_type _handler;
};
// Initialise base with the underlying completion handler
async_result(completion_handler_type &h)
: _base(h._handler)
{
}
using _base::get;
};
//! [async_result2]
asio::experimental::awaitable<void> outcome_(asio::ip::tcp::socket skt)
{
char buffer[1024];
asio::experimental::await_token token = co_await asio::experimental::this_coro::token();
#if 0
{ // debug
using my_result_t = decltype(as_result(token));
asio::async_result<my_result_t, void(error_code, size_t)>::completion_handler_type handler(as_result(token));
asio::async_result<my_result_t, void(error_code, size_t)> result(handler);
error_code ec;
handler(ec, 5);
outcome::result<size_t, error_code> r = co_await result.get();
}
#endif
#if 1
//! [outcome-use-case]
// Asynchronously read data, suspending this coroutine until completion,
// returning the bytes of the data read into the result, or any failure.
outcome::result<size_t, error_code> bytesread = //
co_await skt.async_read_some(asio::buffer(buffer), as_result(token));
// Usage is exactly like ordinary Outcome. Note the lack of exception throw!
if(bytesread.has_error())
{
std::cerr << "Buffer read failed with " << bytesread.error() << std::endl;
return;
}
std::cout << "Read " << bytesread.value() << " bytes into buffer" << std::endl;
//! [outcome-use-case]
#endif
}
int main(void)
{
return 0;
}
|
0 | repos/outcome/doc/src/snippets | repos/outcome/doc/src/snippets/boost-only/asio_integration_1_70.cpp | /* Example of Outcome
(C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include <boost/asio/async_result.hpp>
#include <boost/asio/awaitable.hpp>
#include <boost/asio/use_awaitable.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/outcome.hpp>
#include <vector>
namespace asio = boost::asio;
namespace outcome = boost::outcome_v2;
using byte = char;
using boost::system::error_code;
void old(asio::ip::tcp::socket skt)
{
//! [old-use-case]
// Dynamically allocate a buffer to read into. This must be move-only
// so it can be attached to the completion handler, hence the unique_ptr.
auto buffer = std::make_unique<std::vector<byte>>(1024);
// Begin an asynchronous socket read, upon completion invoke
// the lambda function specified
skt.async_read_some(asio::buffer(buffer->data(), buffer->size()),
// Retain lifetime of the i/o buffer until completion
[buffer = std::move(buffer)](const error_code &ec, size_t bytes) {
// Handle the buffer read
if(ec)
{
std::cerr << "Buffer read failed with " << ec << std::endl;
return;
}
std::cout << "Read " << bytes << " bytes into buffer" << std::endl;
// buffer will be dynamically freed now
});
//! [old-use-case]
}
asio::awaitable<void> new_(asio::ip::tcp::socket skt)
{
//! [new-use-case]
// As coroutines suspend the calling thread whilst an asynchronous
// operation executes, we can use stack allocation instead of dynamic
// allocation
char buffer[1024];
// Asynchronously read data, suspending this coroutine until completion,
// returning the bytes of the data read into the result.
try
{
// The use_awaitable completion token represents the current coroutine
// (requires Coroutines TS)
size_t bytesread = //
co_await skt.async_read_some(asio::buffer(buffer), asio::use_awaitable);
std::cout << "Read " << bytesread << " bytes into buffer" << std::endl;
}
catch(const std::system_error &e)
{
std::cerr << "Buffer read failed with " << e.what() << std::endl;
}
//! [new-use-case]
}
//! [as_result]
namespace detail
{
// Type sugar for wrapping an external completion token
template <class CompletionToken> struct as_result_t
{
CompletionToken token;
};
} // namespace detail
// Factory function for wrapping a third party completion token with
// our type sugar
template <class CompletionToken> //
inline auto as_result(CompletionToken &&token)
{
return detail::as_result_t<std::decay_t<CompletionToken>>{std::forward<CompletionToken>(token)};
};
//! [as_result]
//! [async_result1]
// Tell ASIO about a new kind of completion token, the kind returned
// from our as_result() factory function. This implementation is
// for functions with handlers void(error_code, T) only.
template <class CompletionToken, class T> //
struct asio::async_result<detail::as_result_t<CompletionToken>, //
void(error_code, T)> //
{
// The result type we shall return
using result_type = outcome::result<T, error_code>;
// The awaitable type to be returned by the initiating function,
// the co_await of which will yield a result_type
using return_type = //
typename asio::async_result<CompletionToken, void(result_type)> //
::return_type;
//! [async_result1]
//! [async_result2]
// Wrap a completion handler with void(error_code, T) converting
// handler
template <class Handler>
struct completion_handler {
// Our completion handler spec
void operator()(error_code ec, T v)
{
// Call the underlying completion handler, whose
// completion function is void(result_type)
if(ec)
{
// Complete with a failed result
_handler(result_type(outcome::failure(ec)));
return;
}
// Complete with a successful result
_handler(result_type(outcome::success(v)));
}
Handler _handler;
};
// NOTE the initiate member function initiates the async operation,
// and we want to defer to what would be the initiation of the
// async_result whose handler signature is void(result_type).
template <class Initiation, class... Args>
static return_type
initiate(
Initiation&& init,
detail::as_result_t<CompletionToken>&& token,
Args&&... args)
{
// The async_initiate<CompletionToken, void(result_type)> helper
// function will invoke the async initiation method of the
// async_result<CompletionToken, void(result_type)>, as desired.
// Instead of CompletionToken and void(result_type) we start with
// detail::as_result_t<CompletionToken> and void(ec, T), so
// the inputs need to be massaged then passed along.
return asio::async_initiate<CompletionToken, void(result_type)>(
// create a new initiation which wraps the provided init
[init = std::forward<Initiation>(init)](
auto&& handler, auto&&... initArgs) mutable {
std::move(init)(
// we wrap the handler in the converting completion_handler from
// above, and pass along the args
completion_handler<std::decay_t<decltype(handler)>>{
std::forward<decltype(handler)>(handler)},
std::forward<decltype(initArgs)>(initArgs)...);
},
// the new initiation is called with the handler unwrapped from
// the token, and the original initiation arguments.
token.token,
std::forward<Args>(args)...);
}
};
//! [async_result2]
asio::awaitable<void> outcome_(asio::ip::tcp::socket skt)
{
char buffer[1024];
#if 0
{ // debug
using my_result_t = decltype(as_result(token));
asio::async_result<my_result_t, void(error_code, size_t)>::completion_handler_type handler(as_result(token));
asio::async_result<my_result_t, void(error_code, size_t)> result(handler);
error_code ec;
handler(ec, 5);
outcome::result<size_t, error_code> r = co_await result.get();
}
#endif
#if 1
//! [outcome-use-case]
// Asynchronously read data, suspending this coroutine until completion,
// returning the bytes of the data read into the result, or any failure.
outcome::result<size_t, error_code> bytesread = //
co_await skt.async_read_some(asio::buffer(buffer), as_result(asio::use_awaitable));
// Usage is exactly like ordinary Outcome. Note the lack of exception throw!
if(bytesread.has_error())
{
std::cerr << "Buffer read failed with " << bytesread.error() << std::endl;
return;
}
std::cout << "Read " << bytesread.value() << " bytes into buffer" << std::endl;
//! [outcome-use-case]
#endif
}
int main(void)
{
return 0;
}
|
0 | repos/outcome/doc/src/snippets | repos/outcome/doc/src/snippets/boost-only/error_code_registration.cpp | /* Documentation snippet
(C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits), Luke Peterson <[email protected]> (2 commits), Andrzej Krzemienski <[email protected]> (2 commits) and Andrzej Krzemieński <[email protected]> (1 commit)
File Created: Mar 2017
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License in the accompanying file
Licence.txt or at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
//! [error_code_registration]
#include <boost/system/error_code.hpp> // bring in boost::system::error_code et al
#include <iostream>
#include <string> // for string printing
// This is the custom error code enum
enum class ConversionErrc
{
Success = 0, // 0 should not represent an error
EmptyString = 1,
IllegalChar = 2,
TooLong = 3,
};
namespace boost
{
namespace system
{
// Tell the C++ 11 STL metaprogramming that enum ConversionErrc
// is registered with the standard error code system
template <> struct is_error_code_enum<ConversionErrc> : std::true_type
{
};
} // namespace system
} // namespace boost
namespace detail
{
// Define a custom error code category derived from boost::system::error_category
class ConversionErrc_category : public boost::system::error_category
{
public:
// Return a short descriptive name for the category
virtual const char *name() const noexcept override final { return "ConversionError"; }
// Return what each enum means in text
virtual std::string message(int c) const override final
{
switch(static_cast<ConversionErrc>(c))
{
case ConversionErrc::Success:
return "conversion successful";
case ConversionErrc::EmptyString:
return "converting empty string";
case ConversionErrc::IllegalChar:
return "got non-digit char when converting to a number";
case ConversionErrc::TooLong:
return "the number would not fit into memory";
default:
return "unknown";
}
}
// OPTIONAL: Allow generic error conditions to be compared to me
virtual boost::system::error_condition default_error_condition(int c) const noexcept override final
{
switch(static_cast<ConversionErrc>(c))
{
case ConversionErrc::EmptyString:
return make_error_condition(boost::system::errc::invalid_argument);
case ConversionErrc::IllegalChar:
return make_error_condition(boost::system::errc::invalid_argument);
case ConversionErrc::TooLong:
return make_error_condition(boost::system::errc::result_out_of_range);
default:
// I have no mapping for this code
return boost::system::error_condition(c, *this);
}
}
};
} // namespace detail
// Define the linkage for this function to be used by external code.
// This would be the usual __declspec(dllexport) or __declspec(dllimport)
// if we were in a Windows DLL etc. But for this example use a global
// instance but with inline linkage so multiple definitions do not collide.
#define THIS_MODULE_API_DECL extern inline
// Declare a global function returning a static instance of the custom category
THIS_MODULE_API_DECL const detail::ConversionErrc_category &ConversionErrc_category()
{
static detail::ConversionErrc_category c;
return c;
}
// Overload the global make_error_code() free function with our
// custom enum. It will be found via ADL by the compiler if needed.
inline boost::system::error_code make_error_code(ConversionErrc e)
{
return {static_cast<int>(e), ConversionErrc_category()};
}
int main(void)
{
// Note that we can now supply ConversionErrc directly to error_code
boost::system::error_code ec = ConversionErrc::IllegalChar;
std::cout << "ConversionErrc::IllegalChar is printed by boost::system::error_code as "
<< ec << " with explanatory message " << ec.message() << std::endl;
// We can compare ConversionErrc containing error codes to generic conditions
std::cout << "ec is equivalent to boost::system::errc::invalid_argument = "
<< (ec == std::errc::invalid_argument) << std::endl;
std::cout << "ec is equivalent to boost::system::errc::result_out_of_range = "
<< (ec == std::errc::result_out_of_range) << std::endl;
return 0;
}
//! [error_code_registration]
|
0 | repos | repos/zgml/README.md | # zgml
Tensor library for machine learning, inspired by [ggml](https://github.com/ggerganov/ggml).
|
0 | repos | repos/zgml/build.zig.zon | .{
.name = "zgml",
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",
// This field is optional.
// This is currently advisory only; Zig does not yet do anything
// with this value.
//.minimum_zig_version = "0.11.0",
// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
//.example = .{
// // When updating this field to a new URL, be sure to delete the corresponding
// // `hash`, otherwise you are communicating that you expect to find the old hash at
// // the new URL.
// .url = "https://example.com/foo.tar.gz",
//
// // This is computed from the file contents of the directory of files that is
// // obtained after fetching `url` and applying the inclusion rules given by
// // `paths`.
// //
// // This field is the source of truth; packages do not come from a `url`; they
// // come from a `hash`. `url` is just one of many possible mirrors for how to
// // obtain a package matching this `hash`.
// //
// // Uses the [multihash](https://multiformats.io/multihash/) format.
// .hash = "...",
//
// // When this is provided, the package is found in a directory relative to the
// // build root. In this case the package's hash is irrelevant and therefore not
// // computed. This field and `url` are mutually exclusive.
// .path = "foo",
//},
},
// Specifies the set of files and directories that are included in this package.
// Only files and directories listed here are included in the `hash` that
// is computed for this package.
// Paths are relative to the build root. Use the empty string (`""`) to refer to
// the build root itself.
// A directory listed here means that all files within, recursively, are included.
.paths = .{
// This makes *all* files, recursively, included in this package. It is generally
// better to explicitly list the files and directories instead, to insure that
// fetching from tarballs, file system paths, and version control all result
// in the same contents hash.
"build.zig",
"build.zig.zon",
"src",
"LICENSE",
"README.md",
},
}
|
0 | repos | repos/zgml/build.zig | const std = @import("std");
pub const Options = struct {
use_blas: bool = false,
};
pub fn module(b: *std.Build) *std.Build.Module {
return b.addModule("zgml", .{
.root_source_file = .{ .path = (comptime thisDir()) ++ "/src/zgml.zig" },
.dependencies = &.{
.{ .name = "zgml_options", .module = b.getModule("zgml_options") },
},
});
}
pub const Package = struct {
target: std.Build.ResolvedTarget,
options: Options,
zgml: *std.Build.Module,
zgml_options: *std.Build.Module,
pub fn link(pkg: Package, exe: *std.Build.Step.Compile) void {
exe.root_module.addImport("zgml", pkg.zgml);
exe.root_module.addImport("zgml_options", pkg.zgml_options);
if (pkg.options.use_blas) {
exe.linkLibC();
switch (pkg.target.result.os.tag) {
.windows => {
exe.linkSystemLibrary("libopenblas");
},
.linux => {
exe.linkSystemLibrary("openblas");
},
.macos => {
// exe.addSystemLibrary("openblas");
exe.linkFramework("Accelerate");
},
else => {
@panic("Unsupported host OS");
},
}
}
}
};
pub fn package(
b: *std.Build,
target: std.Build.ResolvedTarget,
optimize: std.builtin.Mode,
args: struct {
options: Options = .{},
},
) Package {
_ = optimize;
const step = b.addOptions();
step.addOption(bool, "use_blas", args.options.use_blas);
const zgml_options = step.createModule();
const zgml = b.addModule("zgml", .{
.root_source_file = .{ .path = thisDir() ++ "/src/main.zig" },
.imports = &.{
.{ .name = "zgml_options", .module = zgml_options },
},
});
return .{
.target = target,
.options = args.options,
.zgml = zgml,
.zgml_options = zgml_options,
};
}
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const use_blas = b.option(bool, "use-blas", "Use BLAS library") orelse false;
_ = package(b, target, optimize, .{ .options = .{ .use_blas = use_blas } });
const test_step = b.step("test", "Run zgml tests");
test_step.dependOn(runTests(b, optimize, target, .{ .use_blas = use_blas }));
// const benchmark_step = b.step("benchmark", "Run zgml benchmarks");
// benchmark_step.dependOn(runBenchmarks(b, target, .{ .use_blas = use_blas }));
}
pub fn runTests(
b: *std.Build,
optimize: std.builtin.Mode,
target: std.Build.ResolvedTarget,
options: Options,
) *std.Build.Step {
const test_exe = b.addTest(.{
.name = "zgml-tests",
.root_source_file = .{ .path = thisDir() ++ "/src/main.zig" },
.target = target,
.optimize = optimize,
});
const zgml_pkg = package(b, target, optimize, .{ .options = options });
zgml_pkg.link(test_exe);
test_exe.root_module.addImport("zgml_options", zgml_pkg.zgml_options);
b.installArtifact(test_exe);
return &b.addRunArtifact(test_exe).step;
}
pub fn runBenchmarks(
b: *std.Build,
target: std.zig.CrossTarget,
options: Options,
) *std.Build.Step {
const exe = b.addExecutable(.{
.name = "zgml-benchmarks",
.root_source_file = .{ .path = thisDir() ++ "/src/benchmark.zig" },
.target = target,
.optimize = .ReleaseFast,
});
const zgml_pkg = package(b, target, .ReleaseFast, .{ .options = options });
zgml_pkg.link(exe);
exe.addModule("zgml", zgml_pkg.zgml);
b.installArtifact(exe);
return &exe.run().step;
}
inline fn thisDir() []const u8 {
return comptime std.fs.path.dirname(@src().file) orelse ".";
}
|
0 | repos/zgml | repos/zgml/src/models.zig | const std = @import("std");
const testing = std.testing;
pub const Linear = @import("models/linear.zig").Model;
pub const Poly = @import("models/poly.zig").Model;
test "ref all decls" {
_ = testing.refAllDecls(Linear(f32));
_ = testing.refAllDecls(Poly(f32));
}
|
0 | repos/zgml | repos/zgml/src/main.zig | const std = @import("std");
const testing = std.testing;
pub usingnamespace @import("tensor.zig");
pub usingnamespace @import("graph.zig");
pub const models = @import("models.zig");
pub const optim = @import("optim.zig");
test "ref all decls" {
_ = testing.refAllDeclsRecursive(models);
_ = testing.refAllDeclsRecursive(optim);
}
|
0 | repos/zgml | repos/zgml/src/loss.zig | const std = @import("std");
const Alloc = std.mem.Allocator;
const Tensor = @import("tensor.zig").Tensor;
pub fn meanSqErr(comptime T: type, x: *Tensor(T), y: *Tensor(T)) *Tensor(T) {
return x.sub(y).sqr().mean(&.{1});
}
|
0 | repos/zgml | repos/zgml/src/optim.zig | const std = @import("std");
pub const adam = @import("optim/adam.zig");
pub const sgd = @import("optim/sgd.zig");
fn implementsOptimizer(comptime Optimizer: type) bool {
return std.meta.hasFn(Optimizer, "init") and
std.meta.hasFn(Optimizer, "deinit") and
std.meta.hasFn(Optimizer, "step") and
std.meta.hasFn(Optimizer, "zeroGrad");
}
test "sgd impls optim" {
const Optimizer = sgd.SGD(f32);
try std.testing.expect(implementsOptimizer(Optimizer));
}
|
0 | repos/zgml | repos/zgml/src/op.zig | pub const Op = enum {
const Self = @This();
none,
dup,
add,
sub,
mul,
div,
sqr,
sqrt,
sum,
mean,
repeat,
abs,
sgn,
neg,
step,
relu,
gelu,
norm,
//
matmul,
matmul_t0,
matmul_t1,
matmul_t0t1,
//
scale,
cpy,
reshape,
view,
permute,
transpose,
get_rows,
// diag_max_inf,
soft_max,
rope,
// conv_1d_1s
// conv_1d_2s
//
// flash_attn,
// flash_ff,
//
pub fn symbol(self: *Self) []const u8 {
return switch (self.*) {
.none => "none",
.dup => "x",
.add => "x+y",
.sub => "x-y",
.mul => "x*y",
.div => "x/y",
.sqr => "x^2",
.sqrt => "√x",
.sum => "Σx",
.mean => "Σx/n",
.repeat => "repeat(x)",
.abs => "abs(x)",
.sgn => "sgn(x)",
.neg => "-x",
.step => "step(x)",
.relu => "relu(x)",
.gelu => "gelu(x)",
.norm => "norm(x)",
//
.matmul => "X*Y",
.matmul_t0 => "XT*Y",
.matmul_t1 => "X*YT",
.matmul_t0t1 => "XT*YT",
//
.scale => "x*v",
.cpy => "x->y",
.reshape => "reshape(x)",
.view => "view(x)",
.permute => "permute(x)",
.transpose => "transpose(x)",
.get_rows => "get_rows(x)",
// diag_max_inf,
.soft_max => "soft_max(x)",
.rope => "rope(x)",
// conv_1d_1s
// conv_1d_2s
//
// flash_attn,
// flash_ff,
//
};
}
};
|
0 | repos/zgml | repos/zgml/src/graph.zig | const std = @import("std");
const tensorlib = @import("./tensor.zig");
const Tensor = tensorlib.Tensor;
const assert = std.debug.assert;
const testing = std.testing;
const Alloc = std.mem.Allocator;
const tac = std.testing.allocator;
pub fn ComputeGraph(comptime T: type) type {
return struct {
const Self = @This();
built_forward: bool = false,
built_backward: bool = false,
forward_node_count: usize = 0,
nodes: std.ArrayList(*Tensor(T)),
grads: std.ArrayList(?*Tensor(T)),
leaves: std.ArrayList(*Tensor(T)),
scratch: std.ArrayList(*Tensor(T)),
/// Set up resources for compute graph.
/// Must call `buildForward` (then optionally `buildBackward`) to be able to do computation.
pub fn init(alloc: Alloc) Self {
const graph: Self = .{
.nodes = std.ArrayList(*Tensor(T)).init(alloc),
.grads = std.ArrayList(?*Tensor(T)).init(alloc),
.leaves = std.ArrayList(*Tensor(T)).init(alloc),
.scratch = std.ArrayList(*Tensor(T)).init(alloc),
};
return graph;
}
/// Clean up all the resources for this compute graph
pub fn deinit(self: *Self) void {
for (self.nodes.items) |t| {
t.deinit();
}
self.nodes.deinit();
if (!self.built_backward) {
for (self.grads.items) |grad_o| {
if (grad_o) |grad| grad.deinit();
}
}
self.grads.deinit();
for (self.leaves.items) |t| {
t.deinit();
}
self.leaves.deinit();
// for (self.scratch.items) |t| {
// t.deinit();
// }
self.scratch.deinit();
}
/// Build a graph where the provided tensor is the final output node
pub fn buildForward(self: *Self, tensor: *Tensor(T)) Alloc.Error!void {
try self.buildForwardHelper(tensor);
self.built_forward = true;
self.forward_node_count = self.nodes.items.len;
}
fn buildForwardHelper(self: *Self, tensor: *Tensor(T)) Alloc.Error!void {
const n_before = self.nodes.items.len;
try self.addParentsThenSelf(tensor);
// tensor should be last node
const n_change = self.nodes.items.len - n_before;
if (n_change > 0) assert(self.nodes.items[self.nodes.items.len - 1] == tensor);
}
/// Build a backward graph
pub fn buildBackward(self: *Self, keep: bool) Alloc.Error!void {
assert(self.nodes.items.len > 0);
// if we are keeping the gradient graph,
// we have to detach the gradient nodes from the original graph
// if (keep) {
// for (self.nodes.items, self.grads.items) |node, grad| {
// if (node.grad) |node_grad| {
// node.grad = try node.copyTensorShape(alloc);
// // if we are detaching the node, the user now owns the memory
// // so we don't need to free it
// grad.?.* = node_grad.*;
// }
// }
// }
const nodes_len = self.nodes.items.len;
for (0..nodes_len) |j| {
const i = nodes_len - j - 1;
const node = self.nodes.items[i];
// because we detached the grad nodes from the original graph, we can afford inplace operations
if (node.grad != null) {
try node.backward(&self.scratch, keep);
}
}
for (0..nodes_len) |j| {
const i = nodes_len - j - 1;
const node = self.nodes.items[i];
if (node.is_param) {
assert(node.grad != null);
try self.buildForwardHelper(node.grad.?);
}
}
self.built_backward = true;
self.resetGrads();
}
fn addParentsThenSelf(self: *Self, tensor: *Tensor(T)) Alloc.Error!void {
// std.debug.print("Visiting {*}\n", .{tensor});
// check if already visited
for (self.nodes.items) |node| {
if (tensor == node) {
return;
}
}
for (self.leaves.items) |node| {
if (tensor == node) {
return;
}
}
// visit parents
if (tensor.src0) |ts0| try self.addParentsThenSelf(ts0);
if (tensor.src1) |ts1| try self.addParentsThenSelf(ts1);
for (tensor.opt) |t_o| {
if (t_o) |t| {
try self.addParentsThenSelf(t);
}
}
if (tensor.op == .none and tensor.grad == null) {
// is leaf
// std.debug.print("Appending {*} to leaves\n", .{tensor});
try self.leaves.append(tensor);
} else {
// std.debug.print("Appending {*} to nodes\n", .{tensor});
try self.nodes.append(tensor);
try self.grads.append(tensor.grad);
}
}
pub fn toGraphViz(self: *const Self) Alloc.Error!std.ArrayList(u8) {
var str = std.ArrayList(u8).init(self.nodes.allocator);
const writer = str.writer();
try writer.print("digraph G {{\n node [shape=box];\n", .{});
for (self.nodes.items) |node| {
// try writer.print(" \"{*}\" [shape=\"none\",label=<<table><tr><td>{s}</td></tr><tr><td>{any}</td></tr></table>>];\n", .{ node, node.op.symbol(), node.data });
try writer.print(" \"{*}\" [shape=\"none\",label=<<table>", .{node});
if (node.op == .none) {
try writer.print("<tr><td>{any}</td></tr>", .{node.data});
} else {
try writer.print("<tr><td>{any}</td></tr>", .{node.data});
try writer.print("<tr><td>{s}</td></tr>", .{node.op.symbol()});
}
if (node.name) |name| {
try writer.print("<tr><td>{s}</td></tr>", .{name});
}
try writer.print("<tr><td>{any}</td></tr>", .{node.ne});
try writer.print("</table>>];\n", .{});
if (node.src0) |src0| {
try writer.print(" \"{*}\" -> \"{*}\";\n", .{ src0, node });
}
if (node.src1) |src1| {
try writer.print(" \"{*}\" -> \"{*}\";\n", .{ src1, node });
}
if (node.grad) |grad| {
try writer.print(" \"{*}\" -> \"{*}\" [style=dashed];\n", .{ node, grad });
}
if (!node.data_owned) {
try writer.print(" \"{*}\" [style=filled fillcolor=gray];\n", .{node});
}
}
for (self.leaves.items) |leaf| {
try writer.print(" \"{*}\" [style=filled fillcolor=green label=\"{any}\"];\n", .{ leaf, leaf.data });
}
for (self.scratch.items) |item| {
try writer.print(" \"{*}\" [style=filled fillcolor=gray label=\"{any}\"];\n", .{ item, item.data });
}
try writer.print("}}\n", .{});
return str;
}
pub fn resetGrads(self: *Self) void {
for (self.grads.items) |grad_o| {
if (grad_o) |grad| {
_ = grad.setAllScalar(0);
}
}
}
pub fn reset(self: *Self) void {
for (self.nodes.items) |node| {
if (node.op != .none) _ = node.setAllScalar(0);
}
}
pub fn compute(self: *const Self) void {
for (self.nodes.items) |node| {
node.compute();
}
}
pub fn computeNoGrad(self: *const Self) void {
for (self.nodes.items[0..self.forward_node_count]) |node| {
node.compute();
}
}
};
}
test "ref all decls" {
_ = testing.refAllDeclsRecursive(ComputeGraph(f32));
}
//#region Tests
test "tensor compute graph - matmul" {
const t1 = try Tensor(f32).init(tac, &.{ 2, 3 });
t1.setData(&[_]f32{
1, 2,
3, 4,
5, 6,
});
t1.setParam();
const t2 = try Tensor(f32).init(tac, &.{ 3, 2 });
t2.setData(&[_]f32{
1, 2, 3,
4, 5, 6,
});
const dst = t1.matMul(false, t2, false);
var g = ComputeGraph(f32).init(tac);
defer g.deinit();
try g.buildForward(dst);
try g.buildBackward(false);
_ = dst.grad.?.setAllScalar(1);
g.compute();
{
const expected = [_]f32{
9, 12, 15,
19, 26, 33,
29, 40, 51,
};
try testing.expectEqualSlices(f32, &expected, dst.data);
}
{
const expected = [_]f32{
6, 15,
6, 15,
6, 15,
};
try testing.expectEqualSlices(f32, &expected, t1.grad.?.data);
}
}
test "build compute graph - forward mul" {
const t0 = try Tensor(f32).init(tac, &.{1});
t0.data[0] = 5;
const t1 = try Tensor(f32).init(tac, &.{1});
t1.data[0] = 6;
const out = t0.mul(t1);
var g = ComputeGraph(f32).init(tac);
defer g.deinit();
try g.buildForward(out);
try g.buildBackward(false);
g.compute();
{
const expected = [_]f32{30};
try testing.expectEqualSlices(f32, &expected, out.data);
}
}
test "build computeNoGrad graph - forward mul" {
const t0 = try Tensor(f32).init(tac, &.{1});
t0.data[0] = 5;
t0.setParam(); // set it, but don't use it
const t1 = try Tensor(f32).init(tac, &.{1});
t1.data[0] = 6;
const out = t0.mul(t1);
var g = ComputeGraph(f32).init(tac);
defer g.deinit();
try g.buildForward(out);
try g.buildBackward(false);
const dummy_val: f32 = -23;
t0.grad.?.data[0] = dummy_val; // dummy value
g.computeNoGrad();
{
const expected = [_]f32{30};
try testing.expectEqualSlices(f32, &expected, out.data);
// t0.grad stays dummy value
try testing.expectEqual(dummy_val, t0.grad.?.data[0]);
}
}
test "build compute graph - forward matMul" {
const t1 = try Tensor(f32).init(tac, &.{ 2, 3 });
t1.setData(&[_]f32{
1, 2,
3, 4,
5, 6,
});
const intermed = t1.matMul(true, t1, false);
const out = intermed.matMul(false, t1, true);
var g = ComputeGraph(f32).init(tac);
defer g.deinit();
try g.buildForward(out);
g.compute();
// {
// const dotviz = try g.toGraphViz();
// defer dotviz.deinit();
// std.debug.print("{s}\n", .{dotviz.items});
// }
{
const expected = [_]f32{
35, 44,
44, 56,
};
try testing.expectEqualSlices(f32, &expected, intermed.data);
}
{
const expected = [_]f32{
123, 281, 439, //
156, 356, 556,
};
try testing.expectEqualSlices(f32, &expected, out.data);
}
}
test "build compute graph - forward mul & add" {
const x = try Tensor(f32).initScalar(tac, 3);
const w = try Tensor(f32).initScalar(tac, 2);
w.setParam();
const b = try Tensor(f32).initScalar(tac, 5);
b.setParam();
const intermed = w.mul(x);
const out = intermed.add(b);
// w*x + b
var g = ComputeGraph(f32).init(tac);
defer g.deinit();
try g.buildForward(out);
g.compute();
// {
// const dotviz = try g.toGraphViz();
// defer dotviz.deinit();
// std.debug.print("{s}\n", .{dotviz.items});
// }
{
const expected = [_]f32{11};
try testing.expectEqualSlices(f32, &expected, out.data);
}
}
test "build compute graph - backward" {
const x = try Tensor(f32).initScalar(tac, 3);
const w = try Tensor(f32).initScalar(tac, 2);
w.setParam();
const b = try Tensor(f32).initScalar(tac, 5);
b.setParam();
const intermed = w.mul(x);
const out = intermed.add(b);
// w*x + b
var g = ComputeGraph(f32).init(tac);
defer g.deinit();
try g.buildForward(out);
try g.buildBackward(false);
_ = out.grad.?.setAllScalar(1);
g.compute();
// {
// const dotviz = try g.toGraphViz();
// defer dotviz.deinit();
// std.debug.print("{s}\n", .{dotviz.items});
// }
{
const expected = [_]f32{11};
try testing.expectEqualSlices(f32, &expected, out.data);
}
{
const expected = [_]f32{3};
try testing.expectEqualSlices(f32, &expected, w.grad.?.data);
}
{
const expected = [_]f32{1};
try testing.expectEqualSlices(f32, &expected, b.grad.?.data);
}
}
fn testSqrFunc(x: *Tensor(f32)) *Tensor(f32) {
return x.sqr();
}
test "build compute graph - backward - testSqrFunc" {
const x = try Tensor(f32).initScalar(tac, 3);
x.setParam();
const out = testSqrFunc(x);
// x^2
var g = ComputeGraph(f32).init(tac);
defer g.deinit();
try g.buildForward(out);
try g.buildBackward(true);
_ = out.grad.?.setAllScalar(1);
g.compute();
{
const expected = [_]f32{9};
try testing.expectEqualSlices(f32, &expected, out.data);
}
{
const expected = [_]f32{6};
try testing.expectEqualSlices(f32, &expected, x.grad.?.data);
}
const iters = 10;
for (0..iters) |_| {
g.compute();
}
// {
// const dotviz = try g.toGraphViz();
// defer dotviz.deinit();
// std.debug.print("{s}\n", .{dotviz.items});
// }
{
const expected = [_]f32{9};
try testing.expectEqualSlices(f32, &expected, out.data);
}
// accumulated gradient
{
const expected = [_]f32{6 * (iters + 1)};
try testing.expectEqualSlices(f32, &expected, x.grad.?.data);
}
}
fn testSqrSumFunc(x: *Tensor(f32)) *Tensor(f32) {
return x.sqr().sumAll();
}
test "build compute graph - backward - testSqrSumFunc" {
const x = try Tensor(f32).init(tac, &.{3});
const data = [_]f32{ 3, 4, 10 };
x.setData(&data);
x.setParam();
const out = testSqrSumFunc(x);
// x^2
var g = ComputeGraph(f32).init(tac);
defer g.deinit();
try g.buildForward(out);
try g.buildBackward(true);
_ = out.grad.?.setAllScalar(1);
g.compute();
{
const expected = [_]f32{125};
try testing.expectEqualSlices(f32, &expected, out.data);
}
{
// 2 * xt
const expected = [_]f32{ 6, 8, 20 };
try testing.expectEqualSlices(f32, &expected, x.grad.?.data);
}
}
test "time speed equation test" {
{
const time = try Tensor(f32).initLinspace(tac, &.{20}, 0, 20);
const c0 = try Tensor(f32).initScalar(tac, 0.75);
const c1 = try Tensor(f32).initScalar(tac, 9.5);
const c2 = try Tensor(f32).initScalar(tac, 1);
const inner = time.sub(c1.repeatLike(time));
const inner2 = inner.sqr();
const inner3 = inner2.mul(c0.repeatLike(inner2));
const speed = inner3.add(c2.repeatLike(inner3));
var g = ComputeGraph(f32).init(tac);
defer g.deinit();
try g.buildForward(speed);
g.compute();
try testing.expectEqual(@as(usize, 20), time.nElems());
for (time.data, speed.data) |t, s| {
const t1 = t - 9.5;
try testing.expectEqual(0.75 * (t1 * t1) + 1, s);
}
}
}
test "a*x^2" {
const x = try Tensor(f32).initScalar(tac, 4);
x.name = "x";
const a = try Tensor(f32).initScalar(tac, 2);
a.name = "a";
a.setParam();
const xsq = x.sqr();
xsq.name = "x^2";
const axsq = xsq.mul(a);
axsq.name = "a*x^2";
var g = ComputeGraph(f32).init(tac);
defer g.deinit();
try g.buildForward(axsq);
try g.buildBackward(false);
g.compute();
try testing.expectEqual(@as(f32, 32), axsq.data[0]);
}
test "arange a*x^2" {
const x = try Tensor(f32).initLinspace(tac, &.{5}, 0, 5);
x.name = "x";
const a = try Tensor(f32).initScalar(tac, 2);
a.name = "a";
a.setParam();
const xsq = x.sqr();
xsq.name = "x^2";
const axsq = xsq.mul(a.repeatLike(xsq));
axsq.name = "a*x^2";
var g = ComputeGraph(f32).init(tac);
defer g.deinit();
try g.buildForward(axsq);
try g.buildBackward(true);
g.compute();
const expected = [_]f32{ 0, 2, 8, 18, 32 };
try testing.expectEqualSlices(f32, &expected, axsq.data);
}
test "arange" {
const t = try Tensor(f32).initLinspace(tac, &.{5}, 0, 5);
t.setParam();
try testing.expectEqual(@as(usize, 5), t.nElems());
const expected = [_]f32{ 0, 1, 2, 3, 4 };
try testing.expectEqualSlices(f32, &expected, t.data);
const out = t.sqr().sumAll();
var g = ComputeGraph(f32).init(tac);
defer g.deinit();
try g.buildForward(out);
try g.buildBackward(true);
out.grad.?.data[0] = 1;
g.compute();
try testing.expectEqual(@as(f32, 30), out.data[0]);
try testing.expectEqualSlices(f32, &.{ 0, 2, 4, 6, 8 }, t.grad.?.data);
const lr = try Tensor(f32).initScalar(tac, 0.01);
defer lr.deinit();
for (0..1000) |_| {
g.reset();
g.resetGrads();
out.grad.?.data[0] = 1;
g.compute();
t.grad.?.computeMul(t.grad.?, lr);
t.computeSub(t, t.grad.?);
}
try testing.expectApproxEqAbs(@as(f32, 0), out.data[0], 0.00001);
}
//#endregion
|
0 | repos/zgml | repos/zgml/src/tensor.zig | const std = @import("std");
const testing = std.testing;
const assert = std.debug.assert;
const builtin = @import("builtin");
const Alloc = std.mem.Allocator;
const tac = std.testing.allocator;
const Op = @import("op.zig").Op;
const opts = @import("zgml_options");
const c = if (opts.use_blas)
switch (builtin.os.tag) {
.linux, .windows => @cImport(@cInclude("cblas.h")),
.macos => @cImport(@cInclude("Accelerate/Accelerate.h")),
else => @cImport(@compileError("Unsupported OS")),
}
else
void;
const max_dims = 4;
const max_opt = 4;
const GELU_COEF_A = 0.044715;
const SQRT_2_OVER_PI = 0.79788456080286535587989211986876;
pub fn Tensor(comptime T: type) type {
return struct {
const Self = @This();
/// Number of dimension
n_dims: u8,
/// Number of elements per axis
/// Format like col, row, batch, channel
ne: [max_dims]usize,
/// Stride per axis
strides: [max_dims]usize,
/// Op that created this tensor.
/// .none by default
op: Op,
is_param: bool,
grad: ?*Self,
src0: ?*Self,
src1: ?*Self,
opt: [max_dims]?*Self,
/// Title of the tensor for debugging
name: ?[]const u8,
/// Data of the tensor
data: []T,
/// Whether the data slice is owned by this tensor
data_owned: bool,
alloc: Alloc,
//#region Setup/Takedown methods
/// Create a tensor.
/// The sizes of each dimension are specified by `ne`.
/// The length of `ne` must be less than or equal to `max_dims`.
/// `ne` is in the format [#cols, #rows, batch, channel] when using all dimensions.
/// The number of columns is the number of elements in a row, thus the data is stored row-major.
/// The number of dimensions will be infered by `ne.len`.
/// Must call `deinit` to free.
pub fn init(alloc: Alloc, ne: []const usize) Alloc.Error!*Self {
return try initHelper(alloc, ne, null);
}
pub fn initLinspace(alloc: Alloc, ne: []const usize, start: T, end: T) Alloc.Error!*Self {
const tensor = try Self.init(alloc, ne);
const denom: T = @floatFromInt(tensor.nElems());
const diff = (end - start) / denom;
for (tensor.data, 0..) |*d, i| {
const num: T = @floatFromInt(i);
d.* = start + diff * num;
}
return tensor;
}
/// Free this tensor and its owned resources
pub fn deinit(self: *Self) void {
if (self.data_owned) self.alloc.free(self.data);
// if (self.grad) |grad| grad.deinit();
self.alloc.destroy(self);
}
// Mark this tensor as an input variable to be used for AD & optim algorithms.
pub fn setParam(self: *Self) void {
self.is_param = true;
assert(self.grad == null);
self.grad = self.copyTensorShape();
}
/// Helper for init.
/// if `data_buf` is null, a new data slice is allocated.
fn initHelper(alloc: Alloc, ne: []const usize, data_buf: ?[]T) Alloc.Error!*Self {
std.debug.assert(ne.len <= max_dims);
const tensor: *Self = try alloc.create(Self);
tensor.* = .{
.n_dims = @truncate(ne.len),
.ne = .{1} ** max_dims,
.strides = .{0} ** max_dims,
.op = .none,
.is_param = false,
.grad = null,
.src0 = null,
.src1 = null,
.data = undefined,
.name = null,
.data_owned = data_buf == null,
.opt = .{null} ** max_opt,
.alloc = alloc,
};
for (ne, 0..) |shape_item, i| {
tensor.ne[i] = shape_item;
}
tensor.strides[0] = 1;
for (1..max_dims) |i| {
tensor.strides[i] = tensor.strides[i - 1] * tensor.ne[i - 1];
}
tensor.data = if (data_buf) |d| d else try alloc.alloc(T, tensor.nElems());
return tensor;
}
/// Init a tensor with a single element `val`
pub fn initScalar(alloc: Alloc, val: T) Alloc.Error!*Self {
const tensor = try Self.init(alloc, &.{1});
return tensor.setAllScalar(val);
}
// init values in the interval [0, 1)
pub fn initRand(alloc: Alloc, rng: *std.rand.Random, ne: []const usize) Alloc.Error!*Self {
const tensor = try Self.init(alloc, ne);
for (tensor.data) |*d| {
d.* = rng.float(T);
}
return tensor;
}
//#endregion
//#region Lazy Operations
/// Create a new tensor as a view of the current tensor's data
pub fn view(self: *Self) *Self {
var t = Self.initHelper(self.alloc, &self.ne, self.data) catch unreachable;
t.op = .view;
t.src0 = self;
t.src1 = null;
t.grad = if (self.grad) |grad| grad.view() else null;
return t;
}
/// Duplicate this tensor (with its shape) without preserving the data
pub fn copyTensorShape(self: *Self) *Self {
return Self.initHelper(self.alloc, &self.ne, null) catch unreachable;
}
fn unaryOp(self: *Self, op: Op, inplace: bool) *Self {
const is_node: bool = !inplace and self.grad != null;
const res = if (inplace) self.view() else self.copyTensorShape();
res.op = op;
res.grad = if (is_node) self.copyTensorShape() else null;
res.src0 = self;
res.src1 = null;
return res;
}
fn binaryOp(self: *Self, other: *Self, op: Op, inplace: bool) *Self {
assert(self.isSameShape(other));
const is_node: bool = !inplace and (self.grad != null or other.grad != null);
const res: *Self = if (inplace) self.view() else self.copyTensorShape();
res.op = op;
res.grad = if (is_node) self.copyTensorShape() else null;
res.src0 = self;
res.src1 = other;
return res;
}
pub fn dup(self: *Self) *Self {
return self.unaryOp(.dup, false);
}
pub fn dupInplace(self: *Self) *Self {
return self.unaryOp(.dup, true);
}
fn addImpl(self: *Self, other: *Self, inplace: bool) *Self {
assert(self.isSameShape(other));
return self.binaryOp(other, .add, inplace);
}
pub fn add(self: *Self, other: *Self) *Self {
return self.addImpl(other, false);
}
pub fn addInplace(self: *Self, other: *Self) *Self {
return self.addImpl(other, true);
}
fn subImpl(self: *Self, other: *Self, inplace: bool) *Self {
return self.binaryOp(other, .sub, inplace);
}
pub fn sub(self: *Self, other: *Self) *Self {
return self.subImpl(other, false);
}
pub fn subInplace(self: *Self, other: *Self) *Self {
return self.subImpl(other, true);
}
/// Element-wise multiply
pub fn mul(self: *Self, other: *Self) *Self {
return self.binaryOp(other, .mul, false);
}
/// Element-wise multiply inplace
pub fn mulInplace(self: *Self, other: *Self) *Self {
return self.binaryOp(other, .mul, true);
}
pub fn div(self: *Self, other: *Self) *Self {
return self.binaryOp(other, .div, false);
}
pub fn divInplace(self: *Self, other: *Self) *Self {
return self.binaryOp(other, .div, true);
}
pub fn sqr(self: *Self) *Self {
return self.unaryOp(.sqr, false);
}
pub fn sqrInplace(self: *Self) *Self {
return self.unaryOp(.sqr, true);
}
pub fn sqrt(self: *Self) *Self {
return self.unaryOp(.sqrt, false);
}
pub fn sqrtInplace(self: *Self) *Self {
return self.unaryOp(.sqrt, true);
}
/// Sum all elements of a tensor
pub fn sumAll(self: *Self) *Self {
return sum(self, &.{1});
}
/// Sum elements of a tensor into the new shape defined by `ne`
pub fn sum(self: *Self, ne: []const usize) *Self {
assert(ne.len <= max_dims);
assert(canSumToShape(self, ne));
const is_node: bool = self.grad != null;
const res = Self.init(self.alloc, ne) catch unreachable;
res.op = .sum;
res.grad = if (is_node) res.copyTensorShape() else null;
res.src0 = self;
res.src1 = null;
return res;
}
pub fn sumInto(self: *Self, other: *Self) *Self {
assert(self.canSumTo(other));
const is_node: bool = self.grad != null;
if (self.isSameShape(other) and !is_node) return self;
const res = other.view();
res.op = .sum;
res.grad = if (is_node) res.copyTensorShape() else null;
res.src0 = self;
res.src1 = null;
return res;
}
pub fn mean(self: *Self, ne: []const usize) *Self {
assert(ne.len <= max_dims);
assert(canSumToShape(self, ne));
const is_node: bool = self.grad != null;
const res = Self.init(self.alloc, ne) catch unreachable;
res.op = .mean;
res.grad = if (is_node) res.copyTensorShape() else null;
res.src0 = self;
res.src1 = null;
return res;
}
pub fn meanInto(self: *Self, other: *Self) *Self {
assert(self.canSumTo(other));
const is_node: bool = self.grad != null;
if (self.isSameShape(other) and !is_node) return self;
const res = other.view();
res.op = .mean;
res.grad = if (is_node) res.copyTensorShape() else null;
res.src0 = self;
res.src1 = null;
return res;
}
fn repeatInto(self: *Self, other: *Self) *Self {
assert(self.canRepeatTo(other));
const is_node: bool = self.grad != null;
if (self.isSameShape(other) and !is_node) return self;
const res = other.view();
res.op = .repeat;
res.grad = if (is_node) res.copyTensorShape() else null;
res.src0 = self;
res.src1 = null;
return res;
}
pub fn repeat(self: *Self, ne: []usize) *Self {
assert(ne.len <= max_dims);
assert(self.canRepeatToShape(ne));
const is_node: bool = self.grad != null;
if (self.hasShape(ne) and !is_node) return self;
const res = Self.init(self.alloc, ne) catch unreachable;
res.op = .repeat;
res.grad = if (self.grad) |grad| grad.repeat(ne) else null;
res.src0 = self;
res.src1 = null;
return res;
}
pub fn repeatLike(self: *Self, other: *Self) *Self {
return repeat(self, &other.ne);
}
pub fn abs(self: *Self) *Self {
return self.unaryOp(.abs, false);
}
pub fn absInplace(self: *Self) *Self {
return self.unaryOp(.abs, true);
}
pub fn sgn(self: *Self) *Self {
return self.unaryOp(.sgn, false);
}
pub fn sgnInplace(self: *Self) *Self {
return self.unaryOp(.sgn, true);
}
pub fn neg(self: *Self) *Self {
return self.unaryOp(.neg, false);
}
pub fn negInplace(self: *Self) *Self {
return self.unaryOp(.neg, true);
}
pub fn step(self: *Self) *Self {
return self.unaryOp(.step, false);
}
pub fn stepInplace(self: *Self) *Self {
return self.unaryOp(.step, true);
}
pub fn relu(self: *Self) *Self {
return self.unaryOp(.relu, false);
}
pub fn reluInplace(self: *Self) *Self {
return self.unaryOp(.relu, true);
}
pub fn gelu(self: *Self) *Self {
return self.unaryOp(.gelu, false);
}
pub fn geluInplace(self: *Self) *Self {
return self.unaryOp(.gelu, true);
}
/// Normalize along rows
pub fn norm(self: *Self) *Self {
return self.unaryOp(.norm, false);
}
/// Normalize along rows inplace
pub fn normInplace(self: *Self) *Self {
// TODO: maybe store epsilon in src1?
return self.unaryOp(.norm, true);
}
pub fn matMul(self: *Self, trans_self: bool, other: *Self, trans_other: bool) *Self {
assert(self.canMatMul(trans_self, other, trans_other));
const is_node = self.grad != null or other.grad != null;
assert(max_dims == 4); // Need to update this function if max_dims changes
const out_ne: [max_dims]usize = lbl: {
break :lbl if (!trans_self and !trans_other)
// out #cols = other #cols, out #rows = self #rows
.{ other.ne[0], self.ne[1], self.ne[2], other.ne[3] }
else if (trans_self and !trans_other)
// out #cols = other #cols, out #rows = self #cols
.{ other.ne[0], self.ne[0], self.ne[2], other.ne[3] }
else if (!trans_self and trans_other)
// out #cols = other #rows, out #rows = self #rows
.{ other.ne[1], self.ne[1], self.ne[2], other.ne[3] }
else
// out #cols = other #rows, out #rows = self #cols
.{ other.ne[1], self.ne[0], self.ne[2], other.ne[3] };
};
const res = Self.init(self.alloc, out_ne[0..@min(self.n_dims, other.n_dims)]) catch unreachable;
res.op = if (trans_self) if (trans_other) .matmul_t0t1 else .matmul_t0 else if (trans_other) .matmul_t1 else .matmul;
res.grad = if (is_node) res.copyTensorShape() else null;
res.src0 = self;
res.src1 = other;
res.assertValidMatMulDims(self, trans_self, other, trans_other);
return res;
}
pub fn scale(self: *Self, other: *Self) *Self {
assert(other.isScalar());
return self.binaryOp(other, .scale, false);
}
pub fn scaleInplace(self: *Self, other: *Self) *Self {
assert(other.isScalar());
return self.binaryOp(other, .scale, true);
}
fn cpyImpl(self: *Self, other: *Self, inplace: bool) *Self {
assert(self.nElems() == other.nElems());
const is_node = !inplace and (self.grad != null or other.grad != null);
assert(!is_node); // TODO: implement backward
const res = if (is_node) other.copyTensorShape() else other.view();
res.op = .cpy;
res.grad = if (is_node) res.copyTensorShape() else null;
res.src0 = self;
res.src1 = other;
return res;
}
pub fn cpyTo(self: *Self, other: *Self) *Self {
return self.cpyImpl(other, true);
}
pub fn cpyInplaceTo(self: *Self, other: *Self) *Self {
return self.cpyImpl(other, true);
}
pub fn reshapeLike(self: *Self, other: *Self) *Self {
assert(self.isContiguous());
assert(other.isContiguous());
assert(self.nElems() == other.nElems());
const is_node = (self.grad != null or other.grad != null);
assert(!is_node); // TODO: implement backward
const res = Self.initHelper(self.alloc, other.ne[0..other.n_dims], self.data) catch unreachable;
res.op = .reshape;
res.grad = if (is_node) res.copyTensorShape() else null;
res.src0 = self;
res.src1 = null;
return res;
}
pub fn reshape(self: *Self, ne: []const usize) *Self {
assert(self.isContiguous());
const neProd = lbl: {
var prod: usize = 0;
for (ne) |item| {
prod *= item;
}
break :lbl prod;
};
assert(self.nElems() == neProd);
const is_node = self.grad != null;
assert(!is_node); // TODO: implement backward
const res = Self.initHelper(self.alloc, ne, self.data) catch unreachable;
res.op = .reshape;
res.grad = if (is_node) res.copyTensorShape() else null;
res.src0 = self;
res.src1 = null;
return res;
}
pub fn transpose(self: *Self) *Self {
const is_node = self.grad != null;
assert(!is_node); // TODO: implement backward
const res = self.view();
res.ne[0] = self.ne[1];
res.ne[1] = self.ne[0];
res.strides[0] = self.strides[1];
res.strides[1] = self.strides[0];
res.op = .transpose;
res.grad = if (is_node) res.copyTensorShape() else null;
res.src0 = self;
res.src1 = null;
return res;
}
//#endregion
//#region Forward Computations for Operations
pub fn computeDup(dst: *Self, src0: *Self) void {
assert(dst.isContiguous());
assert(dst.nElems() == src0.nElems());
if (src0.isContiguous()) {
@memcpy(dst.data, src0.data);
return;
}
// TODO: implement non-contiguous dup
@panic("Unimplemented forward dup for non-contiguous src");
}
pub fn computeAdd(dst: *Self, src0: *Self, src1: *Self) void {
// TODO: add together elements at same position accounting for strides
// TODO: this change needs to happen in all forward functions
if (src0.isSameShape(src1)) {
assert(dst.isSameShape(src0));
for (src0.data, src1.data, dst.data) |src0_item, src1_item, *dst_item| {
dst_item.* = src0_item + src1_item;
}
} else if (src1.isScalar()) {
assert(dst.isSameShape(src0));
for (src0.data, dst.data) |src0_item, *dst_item| {
dst_item.* = src0_item + src1.data[0];
}
} else if (src0.isScalar()) {
assert(dst.isSameShape(src1));
for (src1.data, dst.data) |src1_item, *dst_item| {
dst_item.* = src0.data[0] + src1_item;
}
}
}
pub fn computeSub(dst: *Self, src0: *Self, src1: *Self) void {
// TODO: add together elements at same position accounting for strides
// TODO: this change needs to happen in all forward functions
if (src0.isSameShape(src1)) {
assert(dst.isSameShape(src0));
for (src0.data, src1.data, dst.data) |src0_item, src1_item, *dst_item| {
dst_item.* = src0_item - src1_item;
}
} else if (src1.isScalar()) {
assert(dst.isSameShape(src0));
for (src0.data, dst.data) |src0_item, *dst_item| {
dst_item.* = src0_item - src1.data[0];
}
} else if (src0.isScalar()) {
assert(dst.isSameShape(src1));
for (src1.data, dst.data) |src1_item, *dst_item| {
dst_item.* = src0.data[0] - src1_item;
}
} else {
@panic("Unimplemented forward sub for src sizes");
}
}
pub fn computeMul(dst: *Self, src0: *Self, src1: *Self) void {
if (src0.isScalar()) {
assert(dst.isSameShape(src1));
for (src1.data, dst.data) |src1_item, *dst_item| {
dst_item.* = src0.data[0] * src1_item;
}
} else if (src1.isScalar()) {
assert(dst.isSameShape(src0));
for (src0.data, dst.data) |src0_item, *dst_item| {
dst_item.* = src0_item * src1.data[0];
}
} else {
assert(dst.isSameShape(src0));
assert(src0.isSameShape(src1));
for (src0.data, src1.data, dst.data) |src0_item, src1_item, *dst_item| {
dst_item.* = src0_item * src1_item;
}
}
}
pub fn computeDiv(dst: *Self, src0: *Self, src1: *Self) void {
if (src0.isScalar()) {
assert(dst.isSameShape(src1));
for (src1.data, dst.data) |src1_item, *dst_item| {
dst_item.* = src0.data[0] / src1_item;
}
} else if (src1.isScalar()) {
assert(dst.isSameShape(src0));
for (src0.data, dst.data) |src0_item, *dst_item| {
dst_item.* = src0_item / src1.data[0];
}
} else {
assert(dst.isSameShape(src0));
assert(src0.isSameShape(src1));
for (src0.data, src1.data, dst.data) |src0_item, src1_item, *dst_item| {
dst_item.* = src0_item / src1_item;
}
}
}
// inverse-broadcast mean from src0 to dst
pub fn computeMean(dst: *Self, src0: *Self) void {
assert(max_dims == 4);
assert(src0.canSumTo(dst));
const src0_ne_v: @Vector(4, usize) = src0.ne;
const div_elems: T = @floatFromInt(@reduce(.Mul, src0_ne_v / dst.ne));
for (0..src0.ne[3]) |ne3| {
for (0..src0.ne[2]) |ne2| {
for (0..src0.ne[1]) |ne1| {
for (0..src0.ne[0]) |ne0| {
const src0_nes = @Vector(4, usize){ ne0, ne1, ne2, ne3 };
const dst_nes = src0_nes % dst.ne;
const src0_stride_v: @Vector(4, usize) = src0.strides;
const dst_stride_v: @Vector(4, usize) = dst.strides;
const src0_idx = @reduce(.Add, src0_nes * src0_stride_v);
const dst_idx = @reduce(.Add, dst_nes * dst_stride_v);
dst.data[dst_idx] += src0.data[src0_idx] / div_elems; // we divide every iteration to avoid overflow, rather than summing and dividing once at the end
}
}
}
}
}
// inverse-broadcast sum from src0 to dst
pub fn computeSum(dst: *Self, src0: *Self) void {
assert(max_dims == 4);
assert(src0.canSumTo(dst));
for (0..src0.ne[3]) |ne3| {
for (0..src0.ne[2]) |ne2| {
for (0..src0.ne[1]) |ne1| {
for (0..src0.ne[0]) |ne0| {
const src0_nes = @Vector(4, usize){ ne0, ne1, ne2, ne3 };
const dst_nes = src0_nes % dst.ne;
const src0_stride_v: @Vector(4, usize) = src0.strides;
const dst_stride_v: @Vector(4, usize) = dst.strides;
const src0_idx = @reduce(.Add, src0_nes * src0_stride_v);
const dst_idx = @reduce(.Add, dst_nes * dst_stride_v);
dst.data[dst_idx] += src0.data[src0_idx];
}
}
}
}
}
// broadcast src0 to dst
pub fn computeRepeat(dst: *Self, src0: *Self) void {
assert(max_dims == 4);
assert(src0.canRepeatTo(dst));
for (0..dst.ne[3]) |ne3| {
for (0..dst.ne[2]) |ne2| {
for (0..dst.ne[1]) |ne1| {
for (0..dst.ne[0]) |ne0| {
const nes = @Vector(4, usize){ ne0, ne1, ne2, ne3 };
const src0_nes = nes % src0.ne;
const src0_stride_v: @Vector(4, usize) = src0.strides;
const dst_stride_v: @Vector(4, usize) = dst.strides;
const src0_idx = @reduce(.Add, src0_nes * src0_stride_v);
const dst_idx = @reduce(.Add, nes * dst_stride_v);
dst.data[dst_idx] = src0.data[src0_idx];
}
}
}
}
}
pub fn computeSqr(dst: *Self, src0: *Self) void {
assert(dst.isSameShape(src0));
for (src0.data, dst.data) |src0_item, *dst_item| {
dst_item.* = src0_item * src0_item;
}
}
pub fn computeSqrt(dst: *Self, src0: *Self) void {
assert(dst.isSameShape(src0));
for (src0.data, dst.data) |src0_item, *dst_item| {
dst_item.* = std.math.sqrt(src0_item);
}
}
pub fn computeAbs(dst: *Self, src0: *Self) void {
assert(dst.isSameShape(src0));
for (src0.data, dst.data) |src0_item, *dst_item| {
dst_item.* = @abs(src0_item);
}
}
pub fn computeSgn(dst: *Self, src0: *Self) void {
assert(dst.isSameShape(src0));
for (src0.data, dst.data) |src0_item, *dst_item| {
dst_item.* = if (src0_item > 0) 1 else if (src0_item < 0) -1 else 0;
}
}
pub fn computeNeg(dst: *Self, src0: *Self) void {
assert(dst.isSameShape(src0));
for (src0.data, dst.data) |src0_item, *dst_item| {
dst_item.* = -src0_item;
}
}
pub fn computeStep(dst: *Self, src0: *Self) void {
assert(dst.isSameShape(src0));
for (src0.data, dst.data) |src0_item, *dst_item| {
dst_item.* = if (src0_item > 0) 1 else 0;
}
}
pub fn computeReLu(dst: *Self, src0: *Self) void {
assert(dst.isSameShape(src0));
for (src0.data, dst.data) |src0_item, *dst_item| {
dst_item.* = if (src0_item > 0) src0_item else 0;
}
}
pub fn computeGeLu(dst: *Self, src0: *Self) void {
assert(dst.isSameShape(src0));
for (src0.data, dst.data) |x, *dst_item| {
dst_item.* = 0.5 * x * (1 + std.math.tanh(SQRT_2_OVER_PI * x * (1 + GELU_COEF_A * x * x)));
}
}
pub fn computeNorm(dst: *Self, src0: *Self) void {
_ = src0;
_ = dst;
@panic("Not implemented");
}
pub fn computeRMSNorm(dst: *Self, src0: *Self) void {
_ = src0;
_ = dst;
@panic("Not implemented");
}
fn shouldUseBlasForMatMul(dst: *Self, src0: *Self, src1: *Self) bool {
return src0.isContiguous() and src1.isContiguous() and
(dst.ne[0] >= 32 and dst.ne[1] >= 32 and src1.ne[0] >= 32);
}
fn assertValidMatMulDims(dst: *Self, src0: *Self, trans0: bool, src1: *Self, trans1: bool) void {
// src0 and src1 have same outer two dims
assert(src0.ne[3] == src1.ne[3]);
assert(src0.ne[2] == src1.ne[2]);
assert(dst.ne[2] == src0.ne[2]);
assert(dst.ne[3] == src0.ne[3]);
if (!trans0 and !trans1) {
// src0 and src1 can be matmul'd
// src0 #cols match src1 #rows
assert(src0.ne[0] == src1.ne[1]);
// dst #rows match src0 #rows
assert(dst.ne[1] == src0.ne[1]);
// dst #cols match src1 #cols
assert(dst.ne[0] == src1.ne[0]);
} else if (!trans0 and trans1) {
// same number of #cols (dot product of rows)
assert(src0.ne[0] == src1.ne[0]);
// dst #rows match src0 #rows
assert(dst.ne[1] == src0.ne[1]);
// dst #cols match src1 #rows
assert(dst.ne[0] == src1.ne[1]);
} else if (trans0 and !trans1) {
// same #rows (dot product of columns)
assert(src0.ne[1] == src1.ne[1]);
// dst #rows match src0 #cols
assert(dst.ne[1] == src0.ne[0]);
// dst #cols match src1 #cols
assert(dst.ne[0] == src1.ne[0]);
} else if (trans0 and trans1) {
// transposed src0 and transposed src1 can be matmul'd
// src0 #rows match src1 #cols
assert(src0.ne[1] == src1.ne[0]);
// dst #rows match src0 #cols
assert(dst.ne[1] == src0.ne[0]);
// dst #cols match src1 #rows
assert(dst.ne[0] == src1.ne[1]);
}
}
pub fn computeMatMul(dst: *Self, src0: *Self, comptime trans0: bool, src1: *Self, comptime trans1: bool) void {
assert(max_dims == 4); // must update this func if max_dims changes
dst.assertValidMatMulDims(src0, trans0, src1, trans1);
// dst is not transposed
assert(dst.strides[0] == 1);
assert(dst.strides[0] <= dst.strides[1]);
assert(dst.strides[1] <= dst.strides[2]);
assert(dst.strides[2] <= dst.strides[3]);
const src0_ne3 = src0.ne[3];
const src0_ne2 = src0.ne[2];
const src0_ne1 = src0.ne[1];
const src0_ne0 = src0.ne[0];
const src1_ne1 = src1.ne[1];
const src1_ne0 = src1.ne[0];
const dst_ne0 = dst.ne[0];
const src0_ne1c: c_int = @intCast(src0_ne1);
const src0_ne0c: c_int = @intCast(src0_ne0);
const src1_ne1c: c_int = @intCast(src1_ne1);
const src1_ne0c: c_int = @intCast(src1_ne0);
const dst_ne0c: c_int = @intCast(dst_ne0);
for (0..src0_ne3) |src0_i3| {
for (0..src0_ne2) |src0_i2| {
// mat mul
if (opts.use_blas and T == f32) {
// z = x * yT
c.cblas_sgemm(
c.CblasRowMajor,
if (trans0) c.CblasTrans else c.CblasNoTrans,
if (trans1) c.CblasTrans else c.CblasNoTrans,
if (trans0) src0_ne0c else src0_ne1c, // dst rows
if (trans1) src1_ne1c else src1_ne0c, // dst cols
if (trans0) src0_ne1c else src0_ne0c, // src0 row/col == src1 row/col
1.0, // alpha scaling factor
&src0.data[src0_i3 * src0.strides[3] + src0_i2 * src0.strides[2]],
src0_ne0c, // src0 first dim
&src1.data[src0_i3 * src1.strides[3] + src0_i2 * src1.strides[2]],
src1_ne0c, // src1 first dim
0.0, // beta scaling factor
&dst.data[src0_i3 * dst.strides[3] + src0_i2 * dst.strides[2]],
dst_ne0c, // dst first dim
);
} else if (!trans0 and !trans1) {
for (0..src0_ne1) |src0_i1| { // row0
for (0..src1_ne0) |src1_i0| { // col1
var matmul_sum: T = 0;
for (0..src0_ne0) |src0_i0| { // col0 == row1
const src0_i_v = @Vector(4, usize){ src0_i0, src0_i1, src0_i2, src0_i3 };
const src1_i_v = @Vector(4, usize){ src1_i0, src0_i0, src0_i2, src0_i3 };
const src0_stride_v: @Vector(4, usize) = src0.strides;
const src1_stride_v: @Vector(4, usize) = src1.strides;
const src0_i = @reduce(.Add, src0_i_v * src0_stride_v);
const src1_i = @reduce(.Add, src1_i_v * src1_stride_v);
matmul_sum += src0.data[src0_i] * src1.data[src1_i];
}
// dst col = col1
// dst row = row0
const dst_i_v = @Vector(4, usize){ src1_i0, src0_i1, src0_i2, src0_i3 };
const dst_stride_v: @Vector(4, usize) = dst.strides;
const dst_i = @reduce(.Add, dst_i_v * dst_stride_v);
dst.data[dst_i] = matmul_sum;
}
}
} else if (!trans0 and trans1) {
for (0..src0_ne1) |src0_i1| { // row0
for (0..src1_ne1) |src1_i1| { // row1
var matmul_sum: T = 0;
for (0..src0_ne0) |src0_i0| { // col0 == col1
const src0_i_v = @Vector(4, usize){ src0_i0, src0_i1, src0_i2, src0_i3 };
const src1_i_v = @Vector(4, usize){ src0_i0, src1_i1, src0_i2, src0_i3 }; // different row
const src0_stride_v: @Vector(4, usize) = src0.strides;
const src1_stride_v: @Vector(4, usize) = src1.strides;
const src0_i = @reduce(.Add, src0_i_v * src0_stride_v);
const src1_i = @reduce(.Add, src1_i_v * src1_stride_v);
matmul_sum += src0.data[src0_i] * src1.data[src1_i];
}
// dst col = row1
// dst row = row0
const dst_i_v = @Vector(4, usize){ src1_i1, src0_i1, src0_i2, src0_i3 };
const dst_stride_v: @Vector(4, usize) = dst.strides;
const dst_i = @reduce(.Add, dst_i_v * dst_stride_v);
dst.data[dst_i] = matmul_sum;
}
}
} else if (trans0 and !trans1) {
for (0..src0_ne0) |src0_i0| { // cos0
for (0..src1_ne0) |src1_i0| { // col1
var matmul_sum: T = 0;
for (0..src0_ne1) |src0_i1| { // row0 == row1
const src0_i_v = @Vector(4, usize){ src0_i0, src0_i1, src0_i2, src0_i3 };
const src1_i_v = @Vector(4, usize){ src1_i0, src0_i1, src0_i2, src0_i3 }; // different column
const src0_stride_v: @Vector(4, usize) = src0.strides;
const src1_stride_v: @Vector(4, usize) = src1.strides;
const src0_i = @reduce(.Add, src0_i_v * src0_stride_v);
const src1_i = @reduce(.Add, src1_i_v * src1_stride_v);
matmul_sum += src0.data[src0_i] * src1.data[src1_i];
}
// dst col = col1
// dst row = col0
const dst_i_v = @Vector(4, usize){ src1_i0, src0_i0, src0_i2, src0_i3 };
const dst_stride_v: @Vector(4, usize) = dst.strides;
const dst_i = @reduce(.Add, dst_i_v * dst_stride_v);
dst.data[dst_i] = matmul_sum;
}
}
} else if (trans0 and trans1) {
for (0..src0_ne0) |src0_i0| { // col0
for (0..src1_ne1) |src1_i1| { // row1
var matmul_sum: T = 0;
for (0..src0_ne1) |src0_i1| { // col1 == row0
const src0_i_v = @Vector(4, usize){ src0_i0, src0_i1, src0_i2, src0_i3 };
const src1_i_v = @Vector(4, usize){ src0_i1, src1_i1, src0_i2, src0_i3 };
const src0_stride_v: @Vector(4, usize) = src0.strides;
const src1_stride_v: @Vector(4, usize) = src1.strides;
const src0_i = @reduce(.Add, src0_i_v * src0_stride_v);
const src1_i = @reduce(.Add, src1_i_v * src1_stride_v);
matmul_sum += src0.data[src0_i] * src1.data[src1_i];
}
// dst col = row1
// dst row = col0
const dst_i_v = @Vector(4, usize){ src1_i1, src0_i0, src0_i2, src0_i3 };
const dst_stride_v: @Vector(4, usize) = dst.strides;
const dst_i = @reduce(.Add, dst_i_v * dst_stride_v);
dst.data[dst_i] = matmul_sum;
}
}
}
}
}
}
pub fn compute(tensor: *Tensor(T)) void {
const src0 = tensor.src0;
const src1 = tensor.src1;
switch (tensor.op) {
.none => {},
.dup => tensor.computeDup(src0.?),
.add => tensor.computeAdd(src0.?, src1.?),
.sub => tensor.computeSub(src0.?, src1.?),
.mul => tensor.computeMul(src0.?, src1.?),
.div => tensor.computeDiv(src0.?, src1.?),
.repeat => tensor.computeRepeat(src0.?),
.sqr => tensor.computeSqr(src0.?),
.sqrt => tensor.computeSqrt(src0.?),
.sum => tensor.computeSum(src0.?),
.mean => tensor.computeMean(src0.?),
.abs => tensor.computeAbs(src0.?),
.sgn => tensor.computeSgn(src0.?),
.neg => tensor.computeNeg(src0.?),
.step => tensor.computeStep(src0.?),
.relu => tensor.computeReLu(src0.?),
.gelu => tensor.computeGeLu(src0.?),
.norm => tensor.computeNorm(src0.?),
//
.matmul => tensor.computeMatMul(src0.?, false, src1.?, false),
.matmul_t0 => tensor.computeMatMul(src0.?, true, src1.?, false),
.matmul_t1 => tensor.computeMatMul(src0.?, false, src1.?, true),
.matmul_t0t1 => tensor.computeMatMul(src0.?, true, src1.?, true),
.view => {},
//
// .scale => tensor.computeScale(src0.?),
// .cpy => tensor.computeCpy(src0.?),
// .reshape => tensor.computeReshape(src0.?),
// .permute => tensor.computePermute(src0.?),
// .transpose => tensor.computeTranspose(src0.?),
// .get_rows,
// diag_max_inf,
// .soft_max,
// .rope,
else => @panic("Unimplemented forward OP"),
}
}
//#endregion
//#region Utility Methods
/// Set data of this tensor to elements of data parameter.
/// Number of elements must match.
pub fn setData(self: *Self, data: []const T) void {
assert(@as(usize, data.len) == self.nElems());
@memcpy(self.data, data);
}
/// Sets all values in this tensor to `val`.
/// Returns self for convenience.
pub fn setAllScalar(self: *Self, val: T) *Self {
@memset(self.data, val);
return self;
}
/// Returns number of elements in this tensor
pub fn nElems(self: *Self) usize {
var res: usize = 1;
for (&self.ne) |shape_item| {
res *= shape_item;
}
return res;
}
/// Returns if this tensor is a single scalar value
pub fn isScalar(self: *Self) bool {
for (self.ne[0..]) |shape_item| {
if (shape_item != 1) return false;
}
return true;
}
pub fn isVector(self: *Self) bool {
for (self.ne[1..]) |shape_item| {
if (shape_item != 1) return false;
}
return true;
}
pub fn isMatrix(self: *Self) bool {
for (self.ne[2..]) |shape_item| {
if (shape_item != 1) return false;
}
return true;
}
/// Returns if self can matmul with other.
pub fn canMatMul(self: *Self, transSelf: bool, other: *Self, transOther: bool) bool {
if (self.ne[3] != other.ne[3]) return false; // channels same
if (self.ne[2] != other.ne[2]) return false; // batch same
if (!transSelf and !transOther) {
// self #cols == other #rows
return self.ne[0] == other.ne[1];
} else if (transSelf and !transOther) {
// self #rows == other #rows (column dot product)
return self.ne[1] == other.ne[1];
} else if (!transSelf and transOther) {
// self #cols == other #cols (row dot product)
return self.ne[0] == other.ne[0];
} else {
// self #rows == other #cols
return self.ne[1] == other.ne[0];
}
}
pub fn isContiguous(self: *Self) bool {
if (self.strides[0] != 1) {
return false;
}
for (1..max_dims) |i| {
if (self.strides[i] != self.strides[i - 1] * self.ne[i - 1]) return false;
}
return true;
}
/// Returns if this tensor can be repeated to match the shape of other.
/// This is used for broadcasting.
/// Unlike numpy, broadcasting works where each dimension in other is a multiple of the corresponding dimension in self.
pub fn canRepeatTo(self: *Self, other: *Self) bool {
return self.canRepeatToShape(&other.ne);
}
/// Returns if this tensor can be repeated to match the given shape.
/// This is used for broadcasting.
/// Unlike numpy, broadcasting works where each dimension in other is a multiple of the corresponding dimension in self.
pub fn canRepeatToShape(self: *Self, other_ne: []const usize) bool {
return shapeCanRepeatToShape(&self.ne, other_ne);
}
pub fn canSumTo(self: *Self, other: *Self) bool {
return self.canSumToShape(&other.ne);
}
/// Returns if this tensor can be summed to match the given shape.
/// This is the inverse of canRepeatToShape. It's the opposite of broadcasting.
pub fn canSumToShape(self: *Self, other_ne: []const usize) bool {
return shapeCanRepeatToShape(other_ne, &self.ne);
}
fn shapeCanRepeatToShape(self_ne: []const usize, other_ne: []const usize) bool {
for (self_ne, 0..) |selfNe, i| {
const otherNe = if (i < other_ne.len) other_ne[i] else 1;
if (otherNe % selfNe != 0) return false;
}
return true;
}
/// Returns the element at the given coordinates.
/// Coordinates are given in the format [col#, row#, batch#, channel#]
/// or [col#, row#, batch#] or [col#, row#] or [col#]
pub fn get(self: *Self, coords: []const usize) T {
assert(coords.len == self.n_dims);
var idx: usize = 0;
for (coords, self.strides[0..coords.len]) |coord, stride| {
idx += coord * stride;
}
return self.data[idx];
}
/// Print out a summary of this tensor.
pub fn print(self: *Self) void {
std.debug.print("----{*}----\n", .{self});
std.debug.print("shape: {any}\nstrides: {any}\ndata: {any}\n", .{ self.ne, self.strides, self.data });
std.debug.print("--------------------------\n", .{});
}
/// Checks if two tensors are broadcastable.
/// More info here: https://pytorch.org/docs/stable/notes/broadcasting.html
pub fn isBroadcastable(self: *Self, other: *Self) bool {
for (self.ne, other.ne) |selfNe, otherNe| {
if (selfNe != otherNe and selfNe != 1 and otherNe != 1) {
return false;
}
}
return true;
}
pub fn isSameShape(self: *Self, other: *Self) bool {
return self.hasShape(&other.ne);
}
pub fn hasShape(self: *Self, other_ne: []const usize) bool {
for (self.ne, 0..) |selfNe, i| {
const otherNe = if (i < other_ne.len) other_ne[i] else 1;
if (selfNe != otherNe) {
return false;
}
}
return true;
}
//#endregion
//#region Backward Computations for Operations
fn addToScratchUniq(scratch: *std.ArrayList(*Tensor(T)), tensor: *Tensor(T)) Alloc.Error!void {
for (scratch.items) |item| {
if (item == tensor) return;
}
try scratch.append(tensor);
}
pub fn backward(tensor: *Tensor(T), scratch: *std.ArrayList(*Tensor(T)), inplace: bool) Alloc.Error!void {
const src0_o = tensor.src0;
const src1_o = tensor.src1;
switch (tensor.op) {
.none, .view => {},
.dup => {
const src0 = src0_o.?;
if (src0.grad) |grad| {
const new_grad = grad.addImpl(tensor.grad.?, inplace);
assert(new_grad.isSameShape(grad));
src0.grad = new_grad;
}
},
.add => {
const src0 = src0_o.?;
const src1 = src1_o.?;
if (src0.grad) |grad| {
// TODO: since add can coerce shapes, we need to reduce back to the original shape if they are different
// TODO: this is a problem for all ops that can coerce shapes
// TODO: scalar + vector, for example, when added together, will have the same shape as the vector
// TODO: if the scalar had a grad, the grad would now be the same shape as the vector
// TODO: we need to reduce the grad back to the original shape of the scalar with average
// TODO: Consider broadcastable ops: https://pytorch.org/docs/stable/notes/broadcasting.html
// TODO: http://coldattic.info/post/116/
src0.grad = grad.addImpl(tensor.grad.?, inplace);
}
if (src1.grad) |grad| {
src1.grad = grad.addImpl(tensor.grad.?, inplace);
}
},
.sub => {
const src0 = src0_o.?;
const src1 = src1_o.?;
if (src0.grad) |grad| {
src0.grad = grad.addImpl(tensor.grad.?, inplace);
}
if (src1.grad) |grad| {
src1.grad = grad.subImpl(tensor.grad.?, inplace);
}
},
.mul => {
const src0 = src0_o.?;
const src1 = src1_o.?;
if (src0.grad) |grad| {
const src1_x = src1.mul(tensor.grad.?);
// remove grad
if (src1_x.grad) |gradp| {
gradp.deinit();
src1_x.grad = null;
}
src0.grad = grad.addImpl(src1_x, inplace);
}
if (src1.grad) |grad| {
const src0_x = src0.mul(tensor.grad.?);
// remove grad
if (src0_x.grad) |gradp| {
gradp.deinit();
src0_x.grad = null;
}
src1.grad = grad.addImpl(src0_x, inplace);
}
},
.div => {
const src0 = src0_o.?;
const src1 = src1_o.?;
if (src0.grad) |grad| {
const src1_x = src1.div(tensor.grad.?);
// remove grad
if (src1_x.grad) |gradp| {
gradp.deinit();
src1_x.grad = null;
}
src0.grad = grad.addImpl(src1_x, inplace);
}
if (src1.grad) |grad| {
const src0_x = src0.div(tensor.grad.?);
// remove grad
if (src0_x.grad) |gradp| {
gradp.deinit();
src0_x.grad = null;
}
src1.grad = grad.addImpl(src0_x, inplace);
}
},
.repeat => {
const src0 = src0_o.?;
const t_grad = tensor.grad.?;
if (src0.grad) |grad| {
src0.grad = t_grad.sumInto(grad);
}
},
.sqr => {
const src0 = src0_o.?;
if (src0.grad) |grad| {
// src_grad = 2 * src * out_grad
const t2 = try Self.initScalar(tensor.alloc, 2);
const t2_rep = t2.repeatLike(src0);
const src0_2 = src0.mul(t2_rep);
// remove grad
if (src0_2.grad) |gradp| {
gradp.deinit();
src0_2.grad = null;
}
const src0_2_grad = src0_2.mul(tensor.grad.?);
src0.grad = grad.addImpl(src0_2_grad, inplace);
}
},
// .sqrt,
.sum, .mean => {
const src0 = src0_o.?;
if (src0.grad) |grad| {
src0.grad = grad.addImpl(tensor.grad.?.repeatLike(grad), inplace);
}
},
// .abs,
// .sgn,
// .neg,
// .step,
// .relu,
// .gelu,
// .norm,
//
.matmul => {
const src0 = src0_o.?;
const src1 = src1_o.?;
if (src0.grad) |grad| {
const z = tensor.grad.?.matMul(false, src1, true);
// remove grad
if (z.grad) |gradp| {
gradp.deinit();
z.grad = null;
}
src0.grad = grad.addImpl(z, inplace);
}
if (src1.grad) |grad| {
const z = src0.matMul(true, tensor.grad.?, false);
// remove grad
if (z.grad) |gradp| {
gradp.deinit();
z.grad = null;
}
src1.grad = grad.addImpl(z, inplace);
}
},
// TODO: remove add to scratch
.matmul_t0 => {
const src0 = src0_o.?;
const src1 = src1_o.?;
if (src0.grad) |grad| {
try addToScratchUniq(scratch, tensor.grad.?.matMul(false, src1, true));
src0.grad = grad.addImpl(scratch.items[scratch.items.len - 1], inplace);
try addToScratchUniq(scratch, grad); // move the old one into scratch
}
if (src1.grad) |grad| {
try addToScratchUniq(scratch, src0.matMul(false, tensor.grad.?, false));
src1.grad = grad.addImpl(scratch.items[scratch.items.len - 1], inplace);
try addToScratchUniq(scratch, grad); // move the old one into scratch
}
},
.matmul_t1 => {
const src0 = src0_o.?;
const src1 = src1_o.?;
if (src0.grad) |grad| {
try addToScratchUniq(scratch, tensor.grad.?.matMul(false, src1, false));
src0.grad = grad.addImpl(scratch.items[scratch.items.len - 1], inplace);
try addToScratchUniq(scratch, grad); // move the old one into scratch
}
if (src1.grad) |grad| {
try addToScratchUniq(scratch, src0.matMul(true, tensor.grad.?, false));
src1.grad = grad.addImpl(scratch.items[scratch.items.len - 1], inplace);
try addToScratchUniq(scratch, grad); // move the old one into scratch
}
},
.matmul_t0t1 => {
const src0 = src0_o.?;
const src1 = src1_o.?;
if (src0.grad) |grad| {
try addToScratchUniq(scratch, tensor.grad.?.matMul(true, src1, false));
src0.grad = grad.addImpl(scratch.items[scratch.items.len - 1], inplace);
try addToScratchUniq(scratch, grad); // move the old one into scratch
}
if (src1.grad) |grad| {
try addToScratchUniq(scratch, src0.matMul(false, tensor.grad.?, true));
src1.grad = grad.addImpl(scratch.items[scratch.items.len - 1], inplace);
try addToScratchUniq(scratch, grad); // move the old one into scratch
}
},
// //
// .scale,
// .cpy,
// .reshape,
// .view,
// .permute,
// .transpose,
// .get_rows,
// // diag_max_inf,
// .soft_max,
// .rope,
else => @panic("Unimplemented backward OP"),
}
}
//#endregion
};
}
//#region Tests
test "ref all decls" {
_ = testing.refAllDeclsRecursive(Tensor(f32));
}
//#region Setup/Takedown Tests
test "init" {
{
const tensor = try Tensor(f32).init(tac, &.{ 2, 3 });
defer tensor.deinit();
try testing.expectEqual(@as(usize, 6), tensor.nElems());
const data = [_]f32{
1, 2,
3, 4,
5, 6,
};
@memcpy(tensor.data, &data);
try testing.expectEqual(@as(f32, 1), tensor.get(&.{ 0, 0 }));
try testing.expectEqual(@as(f32, 3), tensor.get(&.{ 0, 1 }));
try testing.expectEqual(@as(f32, 6), tensor.get(&.{ 1, 2 }));
}
{
const tensor = try Tensor(f32).init(tac, &.{ 5, 3, 2 });
defer tensor.deinit();
try testing.expectEqual(@as(usize, 30), tensor.nElems());
}
}
test "initLinspace" {
{
const t = try Tensor(f32).initLinspace(tac, &.{20}, 0, 20);
defer t.deinit();
try testing.expectEqual(@as(usize, 20), t.nElems());
for (t.data, 0..) |v, i| {
try testing.expectEqual(@as(f32, @floatFromInt(i)), v);
}
}
{
const t = try Tensor(f32).initLinspace(tac, &.{20}, 0, 10);
defer t.deinit();
try testing.expectEqual(@as(usize, 20), t.nElems());
for (t.data, 0..) |v, i| {
try testing.expectEqual(@as(f32, @floatFromInt(i)) * 0.5, v);
}
}
}
//#endregion
//#region Utility Method Tests
test "isMatrix" {
{
const tensor = try Tensor(f32).init(tac, &.{ 2, 3 });
defer tensor.deinit();
try testing.expectEqual(@as(usize, 6), tensor.nElems());
try testing.expectEqual(true, tensor.isMatrix());
}
{
const tensor = try Tensor(f32).init(tac, &.{ 2, 3, 4 });
defer tensor.deinit();
try testing.expectEqual(@as(usize, 24), tensor.nElems());
try testing.expectEqual(false, tensor.isMatrix());
}
}
test "isSameShape" {
{
const tensor1 = try Tensor(f32).init(tac, &.{ 2, 3 });
defer tensor1.deinit();
const tensor2 = try Tensor(f32).init(tac, &.{ 3, 2 });
defer tensor2.deinit();
try testing.expectEqual(false, tensor1.isSameShape(tensor2));
try testing.expectEqual(false, tensor2.isSameShape(tensor1));
try testing.expectEqual(true, tensor1.isSameShape(tensor1));
try testing.expectEqual(true, tensor2.isSameShape(tensor2));
}
{
const tensor1 = try Tensor(f32).init(tac, &.{ 2, 4, 3 });
defer tensor1.deinit();
const tensor2 = tensor1.view();
defer tensor2.deinit();
try testing.expectEqual(true, tensor1.isSameShape(tensor2));
}
}
test "canRepeatTo" {
{
const tensor1 = try Tensor(f32).init(tac, &.{ 2, 3 });
defer tensor1.deinit();
const tensor2 = try Tensor(f32).init(tac, &.{ 3, 2 });
defer tensor2.deinit();
try testing.expectEqual(false, tensor1.canRepeatTo(tensor2));
}
{
const tensor1 = try Tensor(f32).init(tac, &.{ 2, 4, 3 });
defer tensor1.deinit();
const tensor2 = try Tensor(f32).init(tac, &.{ 4, 16, 9 });
defer tensor2.deinit();
try testing.expectEqual(true, tensor1.canRepeatTo(tensor2));
}
{
const tensor1 = try Tensor(f32).init(tac, &.{ 2, 3 });
defer tensor1.deinit();
const tensor2 = try Tensor(f32).init(tac, &.{ 2, 3, 5 });
defer tensor2.deinit();
try testing.expectEqual(true, tensor1.canRepeatTo(tensor2));
}
}
//#endregion
//#region Forward Computation Tests
test "compute mean" {
const t1 = try Tensor(f32).init(tac, &.{ 2, 3 });
defer t1.deinit();
t1.setData(&[_]f32{
1, 2,
3, 4,
5, 6,
});
const dst = t1.mean(&.{1});
defer dst.deinit();
dst.computeMean(t1);
const expected = [_]f32{3.5};
for (dst.data, 0..) |v, i| {
try testing.expectApproxEqAbs(expected[i], v, 1e-10);
}
}
test "compute matmul" {
const t1 = try Tensor(f32).init(tac, &.{ 2, 3 });
defer t1.deinit();
t1.setData(&[_]f32{
1, 2,
3, 4,
5, 6,
});
const t2 = try Tensor(f32).init(tac, &.{ 3, 2 });
defer t2.deinit();
t2.setData(&[_]f32{
1, 2, 3,
4, 5, 6,
});
const dst = t1.matMul(false, t2, false);
defer dst.deinit();
dst.computeMatMul(t1, false, t2, false);
const expected = [_]f32{
9, 12, 15,
19, 26, 33,
29, 40, 51,
};
try testing.expectEqualSlices(f32, &expected, dst.data);
}
test "compute matmul_t0" {
const t1 = try Tensor(f32).init(tac, &.{ 2, 3 });
defer t1.deinit();
t1.setData(&[_]f32{
1, 2,
3, 4,
5, 6,
});
const t2 = try Tensor(f32).init(tac, &.{ 2, 3 });
defer t2.deinit();
t2.setData(&[_]f32{
1, 2,
3, 4,
5, 6,
});
const dst = t1.matMul(true, t2, false);
defer dst.deinit();
dst.computeMatMul(t1, true, t2, false);
const expected = [_]f32{
35, 44,
44, 56,
};
try testing.expectEqualSlices(f32, &expected, dst.data);
}
test "compute matmul_t1 2D" {
const t1 = try Tensor(f32).init(tac, &.{ 2, 3 });
t1.setData(&[_]f32{
1, 2,
3, 4,
5, 6,
});
defer t1.deinit();
const t2 = try Tensor(f32).init(tac, &.{ 2, 3 });
t2.setData(&[_]f32{
1, 2,
3, 4,
5, 6,
});
defer t2.deinit();
const dst = t1.matMul(false, t2, true);
defer dst.deinit();
dst.computeMatMul(t1, false, t2, true);
const expected = [_]f32{
5, 11, 17,
11, 25, 39,
17, 39, 61,
};
try testing.expectEqualSlices(f32, &expected, dst.data);
}
test "compute matmul_t1 3D" {
const t1 = try Tensor(f32).init(tac, &.{ 2, 2, 2 });
defer t1.deinit();
const data = [_]f32{
1, 2,
3, 4,
//
5, 6,
7, 8,
};
t1.setData(&data);
try testing.expectEqual(@as(f32, 4), t1.get(&.{ 1, 1, 0 }));
try testing.expectEqual(@as(f32, 7), t1.get(&.{ 0, 1, 1 }));
const dst = t1.matMul(false, t1, true);
defer dst.deinit();
dst.computeMatMul(t1, false, t1, true);
const expected = [_]f32{
5, 11,
11, 25,
//
61, 83,
83, 113,
};
try testing.expectEqualSlices(f32, &expected, dst.data);
}
//#endregion
//#endregion
|
0 | repos/zgml/src | repos/zgml/src/models/linear.zig | const std = @import("std");
const testing = std.testing;
const tac = testing.allocator;
const Tensor = @import("../tensor.zig").Tensor;
const ComputeGraph = @import("../graph.zig").ComputeGraph;
const Alloc = std.mem.Allocator;
const loss = @import("../loss.zig");
const optim = @import("../optim.zig");
pub fn Model(comptime T: type) type {
return struct {
const Self = @This();
cur_batch: usize,
batch_size: usize,
xs_batch: *Tensor(T),
ys_batch: *Tensor(T),
params: [2]*Tensor(T),
g: ComputeGraph(T),
out: *Tensor(T),
loss: *Tensor(T),
pub fn build(alloc: Alloc, m: T, b: T, batch_size: usize) !Self {
var p = Self{
// zig fmt: off
.params = .{
try Tensor(T).initScalar(alloc, m),
try Tensor(T).initScalar(alloc, b),
},
// zig fmt: on
.xs_batch = try Tensor(T).init(alloc, &.{batch_size}),
.ys_batch = try Tensor(T).init(alloc, &.{batch_size}),
.g = ComputeGraph(T).init(alloc),
.out = undefined,
.loss = undefined,
.batch_size = batch_size,
.cur_batch = 0,
};
for (p.params) |param| {
param.setParam();
}
var ne_batch: [1]usize = .{batch_size};
const repeated0 = p.params[0].repeat(ne_batch[0..]);
const mx = p.xs_batch.mul(repeated0);
const repeated1 = p.params[1].repeat(ne_batch[0..]);
p.out = mx.add(repeated1);
p.loss = loss.meanSqErr(T, p.out, p.ys_batch);
{ // for debugging
p.params[0].name = "m";
p.params[1].name = "b";
repeated0.name = "m repeated to batch size";
p.xs_batch.name = "xs batch";
mx.name = "m*x";
repeated1.name = "b repeated to batch size";
p.out.name = "m*x+b";
p.loss.name = "loss";
}
try p.g.buildForward(p.loss);
try p.g.buildBackward(true);
return p;
}
pub fn deinit(self: *Self) void {
self.g.deinit();
}
pub fn compute(self: *Self) void {
self.g.reset();
self.g.resetGrads();
if (self.loss.grad) |grad| _ = grad.setAllScalar(1);
self.g.compute();
}
pub fn train(self: *Self, xs: *Tensor(T), ys: *Tensor(T), n_epochs: usize, batch_size: usize, optimizer: anytype) void {
const n_elems = self.xs_batch.nElems();
const n_batches = xs.nElems() / (n_elems * batch_size);
for (0..n_epochs) |_| {
// TODO: write a random shuffle function for tensors
for (0..n_batches) |b| {
// move batch of xs & ys into batch data
@memcpy(self.xs_batch.data, xs.data[b * self.batch_size ..][0..n_elems]);
@memcpy(self.ys_batch.data, ys.data[b * self.batch_size ..][0..n_elems]);
optimizer.zeroGrad();
self.compute();
optimizer.step();
}
}
}
test "linear model with sgd optim" {
const n = 20;
const time = try Tensor(T).initLinspace(tac, &.{n}, 0, 20);
const true_m = 30;
const speed = try Tensor(T).initLinspace(tac, &.{n}, 0, 20 * true_m);
defer time.deinit();
defer speed.deinit();
var model = try Model(T).build(tac, 0, 0, 1);
defer model.deinit();
var optimizer = try optim.sgd.SGD(T).init(tac, &model.params, 1, model.loss, 1e-3, 0.2);
defer optimizer.deinit();
model.train(time, speed, 10, 1, &optimizer);
try testing.expectApproxEqAbs(@as(T, true_m), model.params[0].data[0], 5e-1);
}
};
}
|
0 | repos/zgml/src | repos/zgml/src/models/poly.zig | const std = @import("std");
const testing = std.testing;
const tac = testing.allocator;
const Tensor = @import("../tensor.zig").Tensor;
const ComputeGraph = @import("../graph.zig").ComputeGraph;
const Alloc = std.mem.Allocator;
const loss = @import("../loss.zig");
const optim = @import("../optim.zig");
pub fn Model(comptime T: type) type {
return struct {
const Self = @This();
cur_batch: usize,
batch_size: usize,
xs_batch: *Tensor(T),
ys_batch: *Tensor(T),
params: std.ArrayList(*Tensor(T)),
g: ComputeGraph(T),
out: *Tensor(T),
loss: *Tensor(T),
pub fn build(alloc: Alloc, max_exp: usize, batch_size: usize) !Self {
var res = Self{
// zig fmt: off
.params = try std.ArrayList(*Tensor(T)).initCapacity(alloc, max_exp+1),
// zig fmt: on
.xs_batch = try Tensor(T).init(alloc, &.{batch_size}),
.ys_batch = try Tensor(T).init(alloc, &.{batch_size}),
.g = ComputeGraph(T).init(alloc),
.out = undefined,
.loss = undefined,
.batch_size = batch_size,
.cur_batch = 0,
};
for (0..max_exp + 1) |_| {
const param = try Tensor(T).initScalar(alloc, 0);
param.setParam();
try res.params.append(param);
}
// mul by xs_batch
var total = try Tensor(T).initScalar(alloc, 0);
var cur_term = try Tensor(T).initScalar(alloc, 1);
for (res.params.items, 0..) |param, i| {
total = total.add(cur_term.mul(param));
if (i < max_exp) cur_term = cur_term.mul(res.xs_batch);
}
res.out = total;
res.loss = loss.meanSqErr(T, res.out, res.ys_batch);
res.loss.name = "loss";
try res.g.buildForward(res.loss);
try res.g.buildBackward(true);
return res;
}
pub fn deinit(self: *Self) void {
self.g.deinit();
self.params.deinit();
}
pub fn compute(self: *Self) void {
self.g.reset();
self.g.resetGrads();
if (self.loss.grad) |grad| _ = grad.setAllScalar(1);
self.g.compute();
}
pub fn train(self: *Self, xs: *Tensor(T), ys: *Tensor(T), n_epochs: usize, batch_size: usize, optimizer: anytype) void {
const n_elems = self.xs_batch.nElems();
const n_batches = xs.nElems() / (n_elems * batch_size);
for (0..n_epochs) |_| {
for (0..n_batches) |b| {
// move batch of xs & ys into batch data
@memcpy(self.xs_batch.data, xs.data[b * self.batch_size ..][0..n_elems]);
@memcpy(self.ys_batch.data, ys.data[b * self.batch_size ..][0..n_elems]);
optimizer.zeroGrad();
self.compute();
optimizer.step();
}
}
}
test "linear poly model with sgd optim" {
const n = 20;
const time = try Tensor(T).initLinspace(tac, &.{n}, 0, 20);
const true_m = 30;
const speed = try Tensor(T).initLinspace(tac, &.{n}, 0, 20 * true_m);
defer time.deinit();
defer speed.deinit();
var model = try Model(T).build(tac, 1, 1);
defer model.deinit();
var optimizer = try optim.sgd.SGD(T).init(tac, model.params.items, 1, model.loss, 1e-3, 0.2);
defer optimizer.deinit();
model.train(time, speed, 10, 1, &optimizer);
try testing.expectApproxEqAbs(@as(T, true_m), model.params.items[1].data[0], 5e-1);
}
// TODO: write more tests for higher polynomials
};
}
|
0 | repos/zgml/src | repos/zgml/src/optim/sgd.zig | const std = @import("std");
const Tensor = @import("../tensor.zig").Tensor;
const Alloc = std.mem.Allocator;
const tac = std.testing.allocator;
const models = @import("../models.zig");
/// Stochastic Gradient Descent optimizer
/// Uses momentum and mini-batches
pub fn SGD(comptime T: type) type {
return struct {
const Self = @This();
params: []const *Tensor(T),
batch_size: usize,
learning_rate: *Tensor(T),
momentum: std.ArrayList(*Tensor(T)),
lr_grad: std.ArrayList(*Tensor(T)),
momentum_decay: *Tensor(T),
loss: *Tensor(T),
pub fn init(
alloc: Alloc,
params: []const *Tensor(T),
batch_size: usize,
loss: *Tensor(T),
learning_rate: T,
momentum_decay: T,
) Alloc.Error!Self {
var res = Self{
.batch_size = batch_size,
.params = params,
.learning_rate = try Tensor(T).initScalar(alloc, learning_rate),
.loss = loss,
.momentum = try std.ArrayList(*Tensor(T)).initCapacity(alloc, params.len),
.lr_grad = try std.ArrayList(*Tensor(T)).initCapacity(alloc, params.len),
.momentum_decay = try Tensor(T).initScalar(alloc, momentum_decay),
};
for (params) |param| {
const mo = try Tensor(T).init(alloc, ¶m.ne);
_ = mo.setAllScalar(0);
res.momentum.appendAssumeCapacity(mo);
const lr_grad = try Tensor(T).init(alloc, ¶m.ne);
_ = lr_grad.setAllScalar(0);
res.lr_grad.appendAssumeCapacity(lr_grad);
}
return res;
}
pub fn deinit(self: *Self) void {
self.learning_rate.deinit();
for (self.momentum.items, self.lr_grad.items) |mo, lrg| {
mo.deinit();
lrg.deinit();
}
self.momentum.deinit();
self.lr_grad.deinit();
self.momentum_decay.deinit();
}
// Must zero grad before calling step
pub fn step(self: *Self) void {
for (self.params, self.momentum.items, self.lr_grad.items) |param, mo, lrg| {
mo.computeMul(mo, self.momentum_decay);
lrg.computeMul(param.grad.?, self.learning_rate);
mo.computeAdd(mo, lrg);
param.computeSub(param, mo);
}
}
pub fn zeroGrad(self: *Self) void {
for (self.params) |param| {
_ = param.grad.?.setAllScalar(0);
}
}
};
}
test "optim - linear model with sgd optim" {
const T = f32;
const n = 100;
const time = try Tensor(T).initLinspace(tac, &.{n}, 0, 20);
const true_m: T = 13.5;
const speed = try Tensor(T).initLinspace(tac, &.{n}, 0, 20 * true_m);
defer time.deinit();
defer speed.deinit();
var model = try models.Linear(T).build(tac, 0, 0, 5);
defer model.deinit();
var optimizer = try SGD(T).init(tac, &model.params, 1, model.loss, 1e-3, 0.2);
defer optimizer.deinit();
model.train(time, speed, 10, 1, &optimizer);
try std.testing.expectApproxEqAbs(@as(T, true_m), model.params[0].data[0], 5e-1);
}
|
0 | repos/zgml/src | repos/zgml/src/optim/adam.zig | // TODO: write Adam optimizer
|
0 | repos/zgml | repos/zgml/.vscode/launch.json | {
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug",
"program": "${workspaceFolder}/zig-out/bin/zgml-tests",
"args": [],
"preLaunchTask": "Build Debug",
"cwd": "${workspaceFolder}"
}
]
} |
0 | repos/zgml | repos/zgml/.vscode/tasks.json | {
"version": "2.0.0",
"tasks": [
{
"label": "Build Debug",
"type": "shell",
"command": "zig build"
}
]
} |
0 | repos | repos/uefi-paint/paint.zig | const uefi = @import("std").os.uefi;
const AbsolutePointerProtocol = uefi.protocols.AbsolutePointerProtocol;
const AbsolutePointerState = uefi.protocols.AbsolutePointerState;
const GraphicsOutputProtocol = uefi.protocols.GraphicsOutputProtocol;
const GraphicsOutputBltPixel = uefi.protocols.GraphicsOutputBltPixel;
const GraphicsOutputBltOperation = uefi.protocols.GraphicsOutputBltOperation;
pub fn main() void {
const boot_services = uefi.system_table.boot_services.?;
var pointer: *AbsolutePointerProtocol = undefined;
var graphics: *GraphicsOutputProtocol = undefined;
var pointer_state = AbsolutePointerState{};
var selected: u4 = 0;
const colors = [16]GraphicsOutputBltPixel{
GraphicsOutputBltPixel{ .blue = 0x00, .green = 0x00, .red = 0x00, .reserved = 0 }, // black
GraphicsOutputBltPixel{ .blue = 0xaa, .green = 0x00, .red = 0x00, .reserved = 0 }, // blue
GraphicsOutputBltPixel{ .blue = 0x00, .green = 0xaa, .red = 0x00, .reserved = 0 }, // green
GraphicsOutputBltPixel{ .blue = 0xaa, .green = 0xaa, .red = 0x00, .reserved = 0 }, // cyan
GraphicsOutputBltPixel{ .blue = 0x00, .green = 0x00, .red = 0xaa, .reserved = 0 }, // red
GraphicsOutputBltPixel{ .blue = 0xaa, .green = 0x00, .red = 0xaa, .reserved = 0 }, // magenta
GraphicsOutputBltPixel{ .blue = 0x00, .green = 0x55, .red = 0xaa, .reserved = 0 }, // brown
GraphicsOutputBltPixel{ .blue = 0xaa, .green = 0xaa, .red = 0xaa, .reserved = 0 }, // gray
GraphicsOutputBltPixel{ .blue = 0x55, .green = 0x55, .red = 0x55, .reserved = 0 }, // dark gray
GraphicsOutputBltPixel{ .blue = 0xff, .green = 0x55, .red = 0x55, .reserved = 0 }, // bright blue
GraphicsOutputBltPixel{ .blue = 0x55, .green = 0xff, .red = 0x55, .reserved = 0 }, // bright green
GraphicsOutputBltPixel{ .blue = 0xff, .green = 0xff, .red = 0x55, .reserved = 0 }, // bright cyan
GraphicsOutputBltPixel{ .blue = 0x55, .green = 0x55, .red = 0xff, .reserved = 0 }, // bright red
GraphicsOutputBltPixel{ .blue = 0xff, .green = 0x55, .red = 0xff, .reserved = 0 }, // bright magenta
GraphicsOutputBltPixel{ .blue = 0x55, .green = 0xff, .red = 0xff, .reserved = 0 }, // yellow
GraphicsOutputBltPixel{ .blue = 0xff, .green = 0xff, .red = 0xff, .reserved = 0 }, // white
};
// Disable watchdog
_ = boot_services.setWatchdogTimer(0, 0, 0, null);
// Set pointers to protocols
_ = boot_services.locateProtocol(&AbsolutePointerProtocol.guid, null, @ptrCast(*?*c_void, &pointer));
_ = boot_services.locateProtocol(&GraphicsOutputProtocol.guid, null, @ptrCast(*?*c_void, &graphics));
// Draw color picker in the uppermost 16th of screen
comptime var i = 0;
inline while (i < 16) : (i += 1) {
var c = [1]GraphicsOutputBltPixel{colors[i]};
_ = graphics.blt(&c, GraphicsOutputBltOperation.BltVideoFill, 0, 0, i * graphics.mode.info.horizontal_resolution / 16, 0, graphics.mode.info.horizontal_resolution / 16, graphics.mode.info.vertical_resolution / 16, 0);
}
var index: usize = undefined;
while (boot_services.waitForEvent(1, @ptrCast([*]uefi.Event, &pointer.wait_for_input), &index) == 0) {
_ = pointer.getState(&pointer_state);
if (graphics.mode.info.vertical_resolution * pointer_state.current_y / (pointer.mode.absolute_max_y - pointer.mode.absolute_min_y) < graphics.mode.info.vertical_resolution / 16) {
// If the color picker has been touched, set selected color
selected = @truncate(u4, 16 * pointer_state.current_x / (pointer.mode.absolute_max_x - pointer.mode.absolute_min_x + 1));
} else if (graphics.mode.info.horizontal_resolution * pointer_state.current_x / (pointer.mode.absolute_max_x - pointer.mode.absolute_min_x) >= 2 and graphics.mode.info.horizontal_resolution * pointer_state.current_x / (pointer.mode.absolute_max_x - pointer.mode.absolute_min_x) < graphics.mode.info.horizontal_resolution - 2 and graphics.mode.info.vertical_resolution * pointer_state.current_y / (pointer.mode.absolute_max_y - pointer.mode.absolute_min_y) < graphics.mode.info.vertical_resolution - 2) {
// Else if touch was at least 2 pixels into the drawing area, draw
var c = [1]GraphicsOutputBltPixel{colors[selected]};
_ = graphics.blt(&c, GraphicsOutputBltOperation.BltVideoFill, 0, 0, graphics.mode.info.horizontal_resolution * pointer_state.current_x / (pointer.mode.absolute_max_x - pointer.mode.absolute_min_x) - 2, graphics.mode.info.vertical_resolution * pointer_state.current_y / (pointer.mode.absolute_max_y - pointer.mode.absolute_min_y) - 2, 5, 5, 0);
}
}
}
|
0 | repos | repos/uefi-paint/build.zig | const Builder = @import("std").build.Builder;
const Target = @import("std").build.Target;
const CrossTarget = @import("std").build.CrossTarget;
const builtin = @import("builtin");
pub fn build(b: *Builder) void {
const exe = b.addExecutable("bootx64", "paint.zig");
exe.setBuildMode(b.standardReleaseOptions());
exe.setTheTarget(Target{
.Cross = CrossTarget{
.arch = builtin.Arch.x86_64,
.os = builtin.Os.uefi,
.abi = builtin.Abi.msvc,
},
});
exe.setOutputDir("EFI/Boot");
b.default_step.dependOn(&exe.step);
}
|
0 | repos | repos/uefi-paint/readme.md | Build with `zig build`, run on a device with a touchscreen.

|
0 | repos | repos/zig_workbench/README.md | .----------------. .----------------. .----------------.
| .--------------. || .--------------. || .--------------. |
| | ________ | || | _________ | || | ____ ____ | |
| | |_ ___ `. | || | |_ ___ | | || | |_ _||_ _| | |
| | | | `. \ | || | | |_ \_| | || | \ \ / / | |
| | | | | | | || | | _| | || | > `' < | |
| | _| |___.' / | || | _| |_ | || | _/ /'`\ \_ | |
| | |________.' | || | |_____| | || | |____||____| | |
| | | || | | || | | |
| '--------------' || '--------------' || '--------------' |
'----------------' '----------------' '----------------'
DarknessFX @ https://dfx.lv | Twitter: @DrkFX
## About
I'm studying and learning [Zig Language](https://ziglearn.org/chapter-0/) (started Nov 19, 2023), sharing here my Zig projects, templates, libs and tools.
Using Windows 10, Zig x86_64 Version : **0.13.0**
> [!NOTE]
> This is a student project, code will run and build without errors (mostly because I just throw away errors), it is not a reference of "*best coding practices*". Suggestions or contributions changing the code to the "*right way and best practices*" are welcome.
## Templates
| Folder | Description | /Subsystem |
| ------------- | ------------- | ------------- |
| **Base** | Template for a console program. | Console |
| **BaseEx** | Template for a console program that hide the console window. | Console |
| **BaseWin** | Template for a Windows program. | Windows |
| **BaseWinEx** | Template for a Windows program, Windows API as submodule. | Windows |
| **BaseImGui** | Template with [Dear ImGui](https://github.com/ocornut/imgui) via [Dear Bindings](https://github.com/dearimgui/dear_bindings). Extra: [ImGui_Memory_Editor](https://github.com/ocornut/imgui_club/tree/main#imgui_memory_editor). Renderers: OpenGL2, OpenGL3, DirectX11, SDL3 OpenGL3, SDL2 OpenGL2, SDL3_Renderer, SDL2_Renderer | Both |
| **BaseLVGL** | Template with [LVGL](https://lvgl.io/) . | Console |
| **Basemicroui** | Template with [microui](https://github.com/rxi/). Renderers: SDL2, Windows GDI. | Windows |
| **BaseRayLib** | Template with [RayLib](https://www.raylib.com/) and [RayGUI](https://github.com/raysan5/raygui). | Console |
| **BaseSDL2** | Template with [SDL2](https://libsdl.org/). | Windows |
| **BaseSDL3** | Template with [SDL3](https://libsdl.org/) Preview. | Windows |
| **BaseOpenGL** | Template with [OpenGL](https://www.opengl.org/) (GL.h). | Windows |
| **BaseGLFW** | Template with [GLFW](https://www.glfw.org/) and [GLAD](https://github.com/Dav1dde/glad/). | Console |
| **BaseDX11** | Template with [DirectX Direct3D 11](https://learn.microsoft.com/en-us/windows/win32/direct3d11/atoc-dx-graphics-direct3d-11). | Windows |
<details>
<summary><ins>Usage</ins></summary>
| Steps | Path example |
| ------------- | ------------- |
| Duplicate the template folder. | C:\zig_workbench\BaseWin Copy\ |
| Rename copy folder to your project name. | C:\zig_workbench\MyZigProgram\ |
| Copy *tools/updateProjectName.bat* to your project Tools folder. | C:\zig_workbench\MyZigProgram\Tools\ |
| Run *updateProjectName.bat*. | C:\zig_workbench\MyZigProgram\Tools\updateProjectName.bat |
| Open *YourProject VSCode Workspace*. | C:\zig_workbench\MyZigProgram\MyZigProgram VSCode Workspace.lnk |
> [!WARNING]
> Current VSCode + ZLS extension do not accept **@cInclude** relative to project folder and will break builds.<br/>
> After open your new project, remember to edit **.zig** files **@cInclude** including your full path and using / folder separator.
Zig have a useful built in feature: *zig init* that creates a basic project. I customized this basic project to fit my use cases, mostly to output to **bin** folder instead of **zig-out\bin**, have main.zig in the project root instead of src folder and use my [VSCode Setup](#about-vscode-tips-and-tricks).
</details>
<details>
<summary><ins>About Dear ImGui</ins></summary>
<pre>Using Dear ImGui Docking 1.90.8 and Dear Bindings (20240607)
All necessary libraries are inside the template.<br/>
Note: When changing renderers, make sure to rename all files (Main.zig, Build.zig, .vscode/Tasks.json).
ImGui_Memory_Editor: Edited from Dear Bindings output. Sample inside all ImGui templates and usage details at <a href="BaseImGui/lib/imgui/cimgui_memory_editor.h" target="_blank">cimgui_memory_editor.h</a></pre>
</details>
<details>
<summary><ins>About LVGL</ins></summary>
<pre>Using <a href="https://github.com/lvgl/lvgl" target="_blank">LVGL from source</a> (20231105, 9.0 Preview).
Used parts of code from <a href="https://github.com/lvgl/lv_port_pc_visual_studio" target="_blank">lv_port_pc_visual_studio</a> (lv_conf and main source).
All necessary libraries are inside the template.
Download Demos and Examples folders from the GitHub source<br/>
(and don't forget to add all .C files necessary to build).</pre>
</details>
<details>
<summary><ins>About microui</ins></summary>
<pre>microui.c and microui.h are inside the project folder.
Normally I would recommend to download from the official repository
but sadly microui is outdated (last update 3 years ago) and I applied
<a href="https://github.com/rxi/microui/pulls" target="_blank">community pull requests</a> to the source code.
It was necessary because the original code crashed with <i>runtime
error: member access within misaligned address</i> and without the
<a href="https://github.com/rxi/microui/issues/19#issuecomment-979063923" target="_blank">fix</a> this project would not work.</pre>
</details>
<details>
<summary><ins>About RayLib</ins></summary>
<pre>Using <a href="https://github.com/raysan5/raylib" target="_blank">RayLib from source</a> (v5.0 from 20231118).
Using <a href="https://github.com/raysan5/raygui" target="_blank">RayGUI from source</a> (v4.1.0-dev from 20240704).
Rebuild raylib.dll because the original was compiled with
/MT (Multi-thread) and Zig is allergic of this kind of DLL,
changing the compile option to /MD solved the problem.
Raygui.h edited to fix a problem with Zig cImport where C
sizeof(int) is treated as [*c]int instead of usize.
</pre>
</details>
<details>
<summary><ins>About SDL2</ins></summary>
<pre> Using SDL2 v2.28.4.
Download SDL2 from: <a href="https://github.com/libsdl-org/SDL/releases/tag/release-2.28.4" target="_blank">GitHub SDL2 Releases Page</a>.
For Windows devs: <a href="https://github.com/libsdl-org/SDL/releases/download/release-2.28.4/SDL2-devel-2.28.4-VC.zip" target="_blank">SDL2-devel-2.28.4-VC.zip 2.57 MB</a>.
Check <a href="https://github.com/DarknessFX/zig_workbench/blob/main/BaseSDL2/lib/SDL2/filelist.txt" target="_blank">BaseSDL2/lib/SDL2/filelist.txt</a> for a description
of the folder structure and expected files path location.</pre>
</details>
<details>
<summary><ins>About SDL3 Preview</ins></summary>
<pre> Built from source in 20240624, version 3.1.2.</pre>
</details>
<details>
<summary><ins>About GLFW and GLAD</ins></summary>
<pre>GLFW 3.3.8 (Win64 Static).
GLAD 2.0 (OpenGL 3.3 Compatibility).
All necessary libraries are inside the template.</pre>
</details>
## Programs
| Folder | Description |
| ------------- | ------------- |
| **zTime** | Similar to Linux TIME command, add zTime in front of your command to get the time it took to execute.<br/> Binary version ready to use is available to download at [Releases Page - zTime v1.0.1](https://github.com/DarknessFX/zig_workbench/releases/tag/zTime_v1.0.1). (console program) |
<details>
<summary><ins>zTime Usage</ins></summary>
<pre> Examples, run in your Command Prompt, Windows Terminal or Powershell:
C:\>zTime zig build
C:\>zTime dir
C:\>zTime bin\ReleaseFast\YourProject.exe<br/>
Suggestion:
Copy zTime.exe to your Zig folder, this way the application will
share the Environment Path and can be executed from anywhere.</pre>
</details>
## Projects
| Folder | Description |
| ------------- | ------------- |
| **ModernOpenGL** | [Mike Shah](https://github.com/MikeShah) [ModernOpenGL](https://www.youtube.com/playlist?list=PLvv0ScY6vfd9zlZkIIqGDeG5TUWswkMox) Youtube Tutorials ported to Zig + SDL3.1.2 OpenGL 4.6. |
<details>
<summary><ins>ModernOpenGL Info</ins></summary>
<pre>All files at Lib/SDL3 are the original ones from SDL Github,
GLAD generated for 4.6 Core. For this project I did not use any
zig binds or wrappers, just plain cImport.
A copy of SDL.h and glad.h exist at Lib root just replacing <> with "",
this change made easier for VSCode and ZLS display auto-complete.
I tried to @cImport GLM OpenGL Mathematics "C" version cGML, @import ziglm
and glm-zig, but each have their own quirks and styles while I'm wanted to
keep the source code similar to the episodes, for this reason I built my
own GLM.ZIG library with just a handful of used functions.
There are some small changes implemented from the original tutorial code,
mostly adding full Translate, Rotate, Scale, Keyboard and Mouse Movement.
The Window Caption have a brief instruction of the keyboard settings and
also, as my default, I used SHIFT+ESC to close the program.</pre>
</details>
## Libraries
| Folder | Description |
| ------------- | ------------- |
| **dos_color.zig** | Helper to output colors to console (std.debug.print) or debug console (OutputDebugString). |
| **string.zig** | WIP String Type. |
<details>
<summary><ins>Libraries usage</ins></summary>
<pre> Create a /lib/ folder in your project folder.
Copy the library file to /lib/ .
Add <q>const libname = @Import("lib/lib_name.zig");</q> to your source code.</pre>
</details>
## Tools
> [!IMPORTANT]
> All tools should be run from **YourProjectFolder\Tools\\** folder, <br/>
> do not run it directly in the main folder.
| Folder | Description |
| ------------- | ------------- |
| **updateProjectName.bat** | Read parent folder name as your ProjectName and replace template references to ProjectName. |
| **buildReleaseStrip.bat** | Call "zig build-exe" with additional options (ReleaseSmall, strip, single-thread), emit assembly (.s), llvm bitcode (.ll, .bc), C header, zig build report. |
| **clean_zig-cache.bat** | Remove zig-cache from **all** sub folders. |
## Tools_ContextMenu
| Folder | Description |
| ------------- | ------------- |
| **zig.ico** | Zig logo Icon file (.ico). (Resolutions 64p, 32p, 16p) |
| **zig_256p.ico** | Zig logo Icon file (.ico) with higher resolutions . (Resolutions 256p, 128p, 64p, 32p, 16p) |
| **zig_contextmenu.bat** | Launcher used by Windows Explorer context menu, copy to Zig folder PATH. |
| **zig_icon.reg** | Associate an icon for .Zig files, add Build, Run, Test to Windows Explorer context menu. [Read more details](/tools/zig_icon.reg) in the file comments. |
| **zig_icon_cascade.reg** | Alternative of zig_icon.reg, groups all options inside a Zig submenu. [Read more details](/tools/zig_icon_cascade.reg) in the file comments. |
Tools to help setup Windows Explorer to apply icons to .ZIG files and add context menu short-cuts to Build, Run and Test.
<details>
<summary><ins>zig_icon.reg - screenshot</ins></summary>
<pre>After run zig_icon.reg, Windows Explorer will look like:<br/>
<img src="/.git_img/zig_icon_contextmenu.png" width="480" /></pre>
</details>
<details>
<summary><ins>zig_icon_cascade.reg - screenshot</ins></summary>
<pre>After run zig_icon_cascade.reg, Windows Explorer will look like:<br/>
<img src="/.git_img/zig_icon_cascade_contextmenu.png" width="480" /></pre>
</details>
## About VSCode (Tips and Tricks)
I'm using [VSCode](https://code.visualstudio.com/download) to program in Zig and using [Zig Language](https://marketplace.visualstudio.com/items?itemName=ziglang.vscode-zig) extension from [ZLS - Zig Language Server](https://github.com/zigtools/zls).
<details>
<summary><ins>Extensions that I use and recommend</ins></summary>
<pre> <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools" target="_blank">C/C++</a> from Microsoft. (**essential to enable Debug mode**.)
<a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools-extension-pack" target="_blank">C/C++ Extension Pack</a> from Microsoft. (non-essential)
<a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools-themes" target="_blank">C/C++ Themes</a>. (non-essential)
<a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.hexeditor" target="_blank">Hex Editor</a> from Microsoft. (**essential in Debug mode**)
<a href="https://marketplace.visualstudio.com/items?itemName=DrMerfy.overtype" target="_blank">OverType</a> from DrMerfy. (non-essential? Add Insert key mode)
<a href="https://marketplace.visualstudio.com/items?itemName=PKief.material-icon-theme" target="_blank">Material Icon Theme</a> from Philipp Kief. (non-essential, but make VSCode looks better)</pre>
</details>
### Ctrl+R is the new F5
I changed a few VSCode keybindings for better use, mostly because Zig offer multiple options for Build, Run, Test, Generate Docs, and I setup VSCode Tasks.json with all available options.
The most important key binding change is **CTRL+T** to open TASKS menu, because VSCode keep the last task as first menu item, just pressing ENTER will: save current file and run the last ask.
Zig Build is fast and *Template/.vscode/launch.json* is already setup so VSCode **F5** key (Start with Debugger) will activate Zig Build and start debug, it works great and fast. But even better is **Zig Run Main**, the way zig run compile and start (without debugger) is a lot faster and helps a lot to iterate and productivity. **CTRL+T, Enter** became one of my most used keyboard shortcut inside VSCode and **CTRL+R** to repeat the last task.<br/>
<details>
<summary><ins>Task menu screenshot</ins></summary>
<img src="/.git_img/vscode_tasks_menu.png" width="480" />
</details>
<details>
<summary><ins>VSCode Keybindings details</ins></summary>
<br/>VSCode Keybindings file location at %APPDATA%\Code\User\keybindings.json<br/><br/>
CTRL+T : Removed showAllSymbols and added runTask.<br/>
Reason : Easy access to Tasks menu and repeatable action to run last action.<br/>
CTRL+R : Removed all bindings.<br/>
Reason: Because this key binding try to reload the current document or display a different menu that also will try to close the current document... If I need I can go to menu File > Open Recent File instead of this shortcut that risk to close what I'm working.<br/>
<pre>
[
{
"key": "ctrl+t",
"command": "-workbench.action.showAllSymbols"
},
{
"key": "ctrl+t",
"command": "workbench.action.tasks.runTask"
}
{
"key": "ctrl+r",
"command": "-workbench.action.reloadWindow",
"when": "isDevelopment"
},
{
"key": "ctrl+r",
"command": "-workbench.action.quickOpenNavigateNextInRecentFilesPicker",
"when": "inQuickOpen && inRecentFilesPicker"
},
{
"key": "ctrl+r",
"command": "-workbench.action.openRecent"
},
{
"key": "ctrl+t",
"command": "workbench.action.tasks.runTask"
},
{
"key": "ctrl+r",
"command": "workbench.action.tasks.reRunTask"
}
]
</pre>
</details>
### Copy your libraries DLL to Zig folder
When using libraries that have .DLL (for example SDL2_ttf.dll) the task Zig Run Main will fail because it cannot find the DLL and the exe was built somewhere in zig-cache. The easier way to fix is to copy the library DLL to your Zig folder.
### Personal observation about VSCode
I have a Love/Hate relationship with VSCode, I only used it to code for Arduino and ESP32 with [Platform.io](https://marketplace.visualstudio.com/items?itemName=platformio.platformio-ide) and the hate is always when the editor try to be "smart and helpful".
Yellow lightbulbs sometimes show up to notify "There are no fix", JSON files organized to easier read key items are reorder because "that is how JSON should be ordered", at least 10% of keys typed are wasted deleting things that VSCode put there to help me. And my favorite gripe: You select a function name in the Intellisense combo, it prints at your source code "YourFunction([cursor here])" BUT it don't display the arguments list, you need to backspace to delete the ( opening parenthesis, type ( and now the tooltip show up with the arguments list.
## Credits
[Zig Language](https://ziglang.org/) from ZigLang.org .<br/>
[SDL2, SDL3](https://libsdl.org/) from libSDL.org .<br/>
[GLFW](https://www.glfw.org) from GLFW.org .<br/>
[GLAD](https://github.com/Dav1dde/glad) from Dav1dde .<br/>
[microui](https://github.com/rxi/microui) from rxi .<br/>
[Dear ImGui](https://github.com/ocornut/imgui) from Omar Cornut .<br/>
[Dear Bindings](https://github.com/dearimgui/dear_bindings) from Ben Carter .<br/>
[LVGL](https://github.com/lvgl/lvgl) from LVGL Kft .<br/>
[ModernOpenGL](https://www.youtube.com/playlist?list=PLvv0ScY6vfd9zlZkIIqGDeG5TUWswkMox) from Mike Shah .<br/>
[RayLib](https://github.com/raysan5/raylib) and [RayGUI](https://github.com/raysan5/raygui) from Ramon Santamaria (@raysan5) .<br/>
## License
MIT - Free for everyone and any use.
DarknessFX @ https://dfx.lv | Twitter: @DrkFX<br/>
https://github.com/DarknessFX/zig_workbench
<details>
<summary><sub><sub>SEO Helper</sub></sub></summary>
<pre>Giving Google a little help pairing Zig + LIB words, because it find my twitter posts easier than this repo:
BaseWinEx = Zig Windows program template with Windows API as submodule.
BaseImGui = Zig ImGui Windows program template with renderers: OpenGL3, DirectX11, SDL3 OpenGL3, SDL2 OpenGL2, SDL3_Renderer, SDL2_Renderer.
BaseLVGL = Zig LVGL Windows program template.
Basemicroui = Zig microui Windows program template with renderers: SDL2, Windows GDI.
BaseRayLib = Zig RayLib and RayGUI Windows program template.
BaseSDL2 = Zig SDL2 Windows program template.
BaseSDL3 = Zig SDL3 Windows program template.
BaseOpenGL = Zig OpenGL GL.h Windows program template.
BaseGLFW = Zig GLFW GLAD Windows program template.
BaseDX11 = Zig DirectX Direct3D 11 DX11 Windows program template.</pre>
</details>
|
0 | repos/zig_workbench | repos/zig_workbench/BaseLVGL/BaseLVGL.rc | #include "windows.h"
IDI_ICON1 ICON "BaseLVGL.ico"
1 VERSIONINFO
FILEVERSION 1,0,0,0
PRODUCTVERSION 1,0,0,0
FILEFLAGSMASK 0x3fL
FILEFLAGS 0x1L
FILEOS 0x4L
FILETYPE 0x1L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904e4"
BEGIN
VALUE "CompanyName", "BaseLVGL"
VALUE "FileDescription", "BaseLVGL"
VALUE "FileVersion", "1.0.0.0"
VALUE "InternalName", "BaseLVGL.exe"
VALUE "LegalCopyright", "Copyleft(c) Created by DarknessFX, http://dfx.lv/ , @DrkFX."
VALUE "OriginalFilename", "BaseLVGL.exe"
VALUE "ProductName", "BaseLVGL"
VALUE "ProductVersion", "1.0.0.0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1252
END
END
|
0 | repos/zig_workbench | repos/zig_workbench/BaseLVGL/main.zig | const std = @import("std");
// NOTE: Need full path to lib/lvgl
pub const lv = @cImport({
@cInclude("lib/lvgl/lvgl.h");
@cInclude("lib/lvgl_drv/win32drv.h");
});
// NOTE:
// - Get Demos and Examples folders from https://github.com/lvgl/lvgl
// - Need to add all .C files for demos or examples to work.
//
// pub const lvexamples = @cImport({
// @cInclude("lib/lvgl/examples/lv_examples.h");
// });
// pub const lvdemos = @cImport({
// @cInclude("lib/lvgl/demos/lv_demos.h");
// });
pub fn main() void {
HideConsole();
lv.lv_init();
lv.lv_tick_set_cb(tick_count_callback);
if (!single_display_mode_initialization()) {
return;
}
//lvdemos.lv_demo_widgets();
// //lv_demo_benchmark(LV_DEMO_BENCHMARK_MODE_RENDER_AND_DRIVER);
while (!lv.lv_win32_quit_signal) {
const time_till_next: u32 = lv.lv_timer_handler();
lv.Sleep(time_till_next);
}
}
fn single_display_mode_initialization() bool {
if (!lv.lv_win32_init(
lv.GetModuleHandleW(null),
lv.SW_SHOW,
800,
480,
lv.LoadIconW(lv.GetModuleHandleW(null), null)))
{
return false;
}
lv.lv_win32_add_all_input_devices_to_group(null);
return true;
}
fn tick_count_callback() callconv(.C) u32 {
return lv.GetTickCount();
}
fn HideConsole() void {
const BUF_TITLE = 1024;
var hwndFound: lv.HWND = undefined;
var pszWindowTitle: [BUF_TITLE:0]lv.CHAR = std.mem.zeroes([BUF_TITLE:0]lv.CHAR);
_ = lv.GetConsoleTitleA(&pszWindowTitle, BUF_TITLE);
hwndFound = lv.FindWindowA(null, &pszWindowTitle);
_ = lv.ShowWindow(hwndFound, lv.SW_HIDE);
} |
0 | repos/zig_workbench | repos/zig_workbench/BaseLVGL/build.zig | const std = @import("std");
pub fn build(b: *std.Build) void {
//Build
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const projectname = "BaseLVGL";
const rootfile = "main.zig";
const exe = b.addExecutable(.{
.name = projectname,
.root_source_file = b.path(rootfile),
.target = target,
.optimize = optimize
});
exe.addWin32ResourceFile(.{
.file = b.path(projectname ++ ".rc"),
.flags = &.{"/c65001"}, // UTF-8 codepage
});
exe.addIncludePath( b.path("lib/lvgl"));
exe.addIncludePath( b.path("lib/lvgl/src"));
exe.addIncludePath( b.path("lib/lvgl_drv/"));
exe.linkSystemLibrary("GDI32");
const c_srcs = .{
"lib/lvgl/src/core/lv_group.c",
"lib/lvgl/src/core/lv_obj_class.c",
"lib/lvgl/src/core/lv_obj_draw.c",
"lib/lvgl/src/core/lv_obj_event.c",
"lib/lvgl/src/core/lv_obj_id_builtin.c",
"lib/lvgl/src/core/lv_obj_pos.c",
"lib/lvgl/src/core/lv_obj_property.c",
"lib/lvgl/src/core/lv_obj_scroll.c",
"lib/lvgl/src/core/lv_obj_style.c",
"lib/lvgl/src/core/lv_obj_style_gen.c",
"lib/lvgl/src/core/lv_obj_tree.c",
"lib/lvgl/src/core/lv_obj.c",
"lib/lvgl/src/core/lv_refr.c",
"lib/lvgl/src/indev/lv_indev.c",
"lib/lvgl/src/indev/lv_indev_scroll.c",
"lib/lvgl/src/stdlib/lv_mem.c",
"lib/lvgl/src/stdlib/builtin/lv_mem_core_builtin.c",
"lib/lvgl/src/stdlib/builtin/lv_string_builtin.c",
"lib/lvgl/src/stdlib/builtin/lv_sprintf_builtin.c",
"lib/lvgl/src/stdlib/builtin/lv_tlsf.c",
"lib/lvgl/src/misc/lv_anim.c",
"lib/lvgl/src/misc/lv_anim_timeline.c",
"lib/lvgl/src/misc/lv_area.c",
"lib/lvgl/src/misc/lv_async.c",
"lib/lvgl/src/misc/lv_bidi.c",
"lib/lvgl/src/misc/lv_cache.c",
"lib/lvgl/src/misc/lv_cache_builtin.c",
"lib/lvgl/src/misc/lv_color.c",
"lib/lvgl/src/misc/lv_color_op.c",
"lib/lvgl/src/misc/lv_event.c",
"lib/lvgl/src/misc/lv_fs.c",
"lib/lvgl/src/misc/lv_ll.c",
"lib/lvgl/src/misc/lv_log.c",
"lib/lvgl/src/misc/lv_lru.c",
"lib/lvgl/src/misc/lv_math.c",
"lib/lvgl/src/misc/lv_palette.c",
"lib/lvgl/src/misc/lv_profiler_builtin.c",
"lib/lvgl/src/misc/lv_style.c",
"lib/lvgl/src/misc/lv_style_gen.c",
"lib/lvgl/src/misc/lv_templ.c",
"lib/lvgl/src/misc/lv_text.c",
"lib/lvgl/src/misc/lv_text_ap.c",
"lib/lvgl/src/misc/lv_timer.c",
"lib/lvgl/src/misc/lv_utils.c",
"lib/lvgl/src/libs/fsdrv/lv_fs_win32.c",
"lib/lvgl/src/others/file_explorer/lv_file_explorer.c",
"lib/lvgl/src/others/fragment/lv_fragment.c",
"lib/lvgl/src/others/fragment/lv_fragment_manager.c",
"lib/lvgl/src/others/gridnav/lv_gridnav.c",
"lib/lvgl/src/others/ime/lv_ime_pinyin.c",
"lib/lvgl/src/others/imgfont/lv_imgfont.c",
"lib/lvgl/src/others/monkey/lv_monkey.c",
"lib/lvgl/src/others/observer/lv_observer.c",
"lib/lvgl/src/others/snapshot/lv_snapshot.c",
"lib/lvgl/src/others/sysmon/lv_sysmon.c",
"lib/lvgl/src/layouts/lv_layout.c",
"lib/lvgl/src/layouts/flex/lv_flex.c",
"lib/lvgl/src/layouts/grid/lv_grid.c",
"lib/lvgl/src/tick/lv_tick.c",
"lib/lvgl/src/draw/lv_draw.c",
"lib/lvgl/src/draw/lv_draw_arc.c",
"lib/lvgl/src/draw/lv_draw_buf.c",
"lib/lvgl/src/draw/lv_draw_image.c",
"lib/lvgl/src/draw/lv_draw_label.c",
"lib/lvgl/src/draw/lv_draw_line.c",
"lib/lvgl/src/draw/lv_draw_mask.c",
"lib/lvgl/src/draw/lv_draw_rect.c",
"lib/lvgl/src/draw/lv_draw_triangle.c",
"lib/lvgl/src/draw/lv_image_buf.c",
"lib/lvgl/src/draw/lv_image_decoder.c",
"lib/lvgl/src/draw/sw/lv_draw_sw.c",
"lib/lvgl/src/draw/sw/lv_draw_sw_arc.c",
"lib/lvgl/src/draw/sw/lv_draw_sw_bg_img.c",
"lib/lvgl/src/draw/sw/lv_draw_sw_border.c",
"lib/lvgl/src/draw/sw/lv_draw_sw_box_shadow.c",
"lib/lvgl/src/draw/sw/lv_draw_sw_fill.c",
"lib/lvgl/src/draw/sw/lv_draw_sw_gradient.c",
"lib/lvgl/src/draw/sw/lv_draw_sw_img.c",
"lib/lvgl/src/draw/sw/lv_draw_sw_letter.c",
"lib/lvgl/src/draw/sw/lv_draw_sw_line.c",
"lib/lvgl/src/draw/sw/lv_draw_sw_mask.c",
"lib/lvgl/src/draw/sw/lv_draw_sw_mask_rect.c",
"lib/lvgl/src/draw/sw/lv_draw_sw_transform.c",
"lib/lvgl/src/draw/sw/lv_draw_sw_triangle.c",
"lib/lvgl/src/draw/sw/blend/lv_draw_sw_blend.c",
"lib/lvgl/src/draw/sw/blend/lv_draw_sw_blend_to_argb8888.c",
"lib/lvgl/src/draw/sw/blend/lv_draw_sw_blend_to_rgb565.c",
"lib/lvgl/src/draw/sw/blend/lv_draw_sw_blend_to_rgb888.c",
"lib/lvgl/src/display/lv_display.c",
"lib/lvgl/src/osal/lv_os_none.c",
"lib/lvgl/src/font/lv_font.c",
"lib/lvgl/src/font/lv_font_fmt_txt.c",
"lib/lvgl/src/font/lv_font_montserrat_14.c",
"lib/lvgl/src/themes/lv_theme.c",
"lib/lvgl/src/themes/basic/lv_theme_basic.c",
"lib/lvgl/src/themes/default/lv_theme_default.c",
"lib/lvgl/src/themes/mono/lv_theme_mono.c",
"lib/lvgl/src/widgets/arc/lv_arc.c",
"lib/lvgl/src/widgets/bar/lv_bar.c",
"lib/lvgl/src/widgets/button/lv_button.c",
"lib/lvgl/src/widgets/buttonmatrix/lv_buttonmatrix.c",
"lib/lvgl/src/widgets/calendar/lv_calendar.c",
"lib/lvgl/src/widgets/calendar/lv_calendar_header_arrow.c",
"lib/lvgl/src/widgets/calendar/lv_calendar_header_dropdown.c",
"lib/lvgl/src/widgets/canvas/lv_canvas.c",
"lib/lvgl/src/widgets/chart/lv_chart.c",
"lib/lvgl/src/widgets/checkbox/lv_checkbox.c",
"lib/lvgl/src/widgets/dropdown/lv_dropdown.c",
"lib/lvgl/src/widgets/image/lv_image.c",
"lib/lvgl/src/widgets/imgbtn/lv_imgbtn.c",
"lib/lvgl/src/widgets/keyboard/lv_keyboard.c",
"lib/lvgl/src/widgets/label/lv_label.c",
"lib/lvgl/src/widgets/led/lv_led.c",
"lib/lvgl/src/widgets/line/lv_line.c",
"lib/lvgl/src/widgets/list/lv_list.c",
"lib/lvgl/src/widgets/menu/lv_menu.c",
"lib/lvgl/src/widgets/msgbox/lv_msgbox.c",
"lib/lvgl/src/widgets/objx_templ/lv_objx_templ.c",
"lib/lvgl/src/widgets/roller/lv_roller.c",
"lib/lvgl/src/widgets/scale/lv_scale.c",
"lib/lvgl/src/widgets/slider/lv_slider.c",
"lib/lvgl/src/widgets/span/lv_span.c",
"lib/lvgl/src/widgets/spinbox/lv_spinbox.c",
"lib/lvgl/src/widgets/spinner/lv_spinner.c",
"lib/lvgl/src/widgets/switch/lv_switch.c",
"lib/lvgl/src/widgets/table/lv_table.c",
"lib/lvgl/src/widgets/tabview/lv_tabview.c",
"lib/lvgl/src/widgets/textarea/lv_textarea.c",
"lib/lvgl/src/widgets/tileview/lv_tileview.c",
"lib/lvgl/src/widgets/win/lv_win.c"
};
exe.addCSourceFile(.{
.file = b.path("lib/lvgl/src/lv_init.c"),
.flags = &.{ "-Wno-implicit-function-declaration" }
});
inline for (c_srcs) |c_cpp| {
exe.addCSourceFile(.{
.file = b.path(c_cpp),
.flags = &.{ }
});
}
exe.addCSourceFile(.{
.file = b.path("lib/lvgl_drv/win32drv.c"),
.flags = &.{
"-Wno-macro-redefined",
"-Wno-extern-initializer",
"-Wno-incompatible-pointer-types",
"-Wno-implicit-function-declaration",
"-Wno-int-conversion",
"-Wno-int-to-pointer-cast"
}
});
exe.linkLibC();
switch (optimize) {
.Debug => b.exe_dir = "bin/Debug",
.ReleaseSafe => b.exe_dir = "bin/ReleaseSafe",
.ReleaseFast => b.exe_dir = "bin/ReleaseFast",
.ReleaseSmall => b.exe_dir = "bin/ReleaseSmall"
//else => b.exe_dir = "bin/Else",
}
b.installArtifact(exe);
//Run
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
//Tests
const unit_tests = b.addTest(.{
.root_source_file = b.path(rootfile),
.target = target,
.optimize = optimize,
});
const run_unit_tests = b.addRunArtifact(unit_tests);
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_unit_tests.step);
}
|
0 | repos/zig_workbench/BaseLVGL/lib | repos/zig_workbench/BaseLVGL/lib/lvgl_drv/lv_port_indev.c | // SPDX-License-Identifier: MIT
#include "lv_port_indev.h"
#include "lvgl.h"
#ifdef NXDK
#include <SDL.h>
#else
#include <SDL2/SDL.h>
#endif
static lv_indev_drv_t indev_drv_gamepad;
static lv_indev_drv_t indev_drv_mouse;
static lv_indev_t *indev_mouse;
static lv_indev_t *indev_keypad;
static lv_obj_t *mouse_cursor;
static SDL_GameController *pad = NULL;
static int mouse_x, mouse_y;
static lv_quit_event_t quit_event = LV_QUIT_NONE;
static bool mouse_event = false;
static bool mouse_pressed = false;
#ifndef MOUSE_SENSITIVITY
#define MOUSE_SENSITIVITY 50 // pixels per input poll LV_INDEV_DEF_READ_PERIOD
#endif
#ifndef MOUSE_DEADZONE
#define MOUSE_DEADZONE 10 // Percent
#endif
#ifndef LVGL_USE_CUSTOM_CONTROLLER_MAP
static gamecontroller_map_t lvgl_gamecontroller_map[] =
{
{.sdl_map = SDL_CONTROLLER_BUTTON_A, .lvgl_map = LV_KEY_ENTER},
{.sdl_map = SDL_CONTROLLER_BUTTON_B, .lvgl_map = LV_KEY_ESC},
{.sdl_map = SDL_CONTROLLER_BUTTON_X, .lvgl_map = LV_KEY_BACKSPACE},
{.sdl_map = SDL_CONTROLLER_BUTTON_Y, .lvgl_map = LV_KEY_HOME},
{.sdl_map = SDL_CONTROLLER_BUTTON_BACK, .lvgl_map = LV_KEY_PREV},
{.sdl_map = SDL_CONTROLLER_BUTTON_GUIDE, .lvgl_map = 0},
{.sdl_map = SDL_CONTROLLER_BUTTON_START, .lvgl_map = LV_KEY_NEXT},
{.sdl_map = SDL_CONTROLLER_BUTTON_LEFTSTICK, .lvgl_map = LV_KEY_PREV},
{.sdl_map = SDL_CONTROLLER_BUTTON_RIGHTSTICK, .lvgl_map = LV_KEY_NEXT},
{.sdl_map = SDL_CONTROLLER_BUTTON_LEFTSHOULDER, .lvgl_map = LV_KEY_PREV},
{.sdl_map = SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, .lvgl_map = LV_KEY_NEXT},
{.sdl_map = SDL_CONTROLLER_BUTTON_DPAD_UP, .lvgl_map = LV_KEY_UP},
{.sdl_map = SDL_CONTROLLER_BUTTON_DPAD_DOWN, .lvgl_map = LV_KEY_DOWN},
{.sdl_map = SDL_CONTROLLER_BUTTON_DPAD_LEFT, .lvgl_map = LV_KEY_LEFT},
{.sdl_map = SDL_CONTROLLER_BUTTON_DPAD_RIGHT, .lvgl_map = LV_KEY_RIGHT}};
#else
extern gamecontroller_map_t lvgl_gamecontroller_map[];
#endif
#ifndef LVGL_USE_CUSTOM_KEYBOARD_MAP
static keyboard_map_t lvgl_keyboard_map[] =
{
{.sdl_map = SDLK_ESCAPE, .lvgl_map = LV_KEY_ESC},
{.sdl_map = SDLK_BACKSPACE, .lvgl_map = LV_KEY_BACKSPACE},
{.sdl_map = SDLK_HOME, .lvgl_map = LV_KEY_HOME},
{.sdl_map = SDLK_RETURN, .lvgl_map = LV_KEY_ENTER},
{.sdl_map = SDLK_PAGEDOWN, .lvgl_map = LV_KEY_PREV},
{.sdl_map = SDLK_PAGEUP, .lvgl_map = LV_KEY_NEXT},
{.sdl_map = SDLK_TAB, .lvgl_map = LV_KEY_NEXT},
{.sdl_map = SDLK_UP, .lvgl_map = LV_KEY_UP},
{.sdl_map = SDLK_DOWN, .lvgl_map = LV_KEY_DOWN},
{.sdl_map = SDLK_LEFT, .lvgl_map = LV_KEY_LEFT},
{.sdl_map = SDLK_RIGHT, .lvgl_map = LV_KEY_RIGHT}};
#else
extern keyboard_map_t lvgl_keyboard_map[];
#endif
lv_quit_event_t lv_get_quit()
{
return quit_event;
}
void lv_set_quit(lv_quit_event_t event)
{
quit_event = event;
}
static void mouse_read(lv_indev_drv_t *indev_drv_gamepad, lv_indev_data_t *data)
{
if (pad == NULL)
{
return;
}
data->state = (mouse_pressed) ? LV_INDEV_STATE_PRESSED : LV_INDEV_STATE_RELEASED;
// Event for a USB mouse
if (mouse_event)
{
uint32_t buttons = SDL_GetMouseState(&mouse_x, &mouse_y);
data->point.x = mouse_x;
data->point.y = mouse_y;
data->state |= (buttons & SDL_BUTTON_LMASK) ? LV_INDEV_STATE_PRESSED : LV_INDEV_STATE_RELEASED;
mouse_event = false;
}
// From gamecontroller
else
{
int x = SDL_GameControllerGetAxis(pad, SDL_CONTROLLER_AXIS_LEFTX);
int y = SDL_GameControllerGetAxis(pad, SDL_CONTROLLER_AXIS_LEFTY);
if (SDL_abs(x) > (MOUSE_DEADZONE * 32768) / 100)
{
mouse_x += (x * MOUSE_SENSITIVITY) / 32768;
if (mouse_x < 0)
mouse_x = 0;
if (mouse_x > 640)
mouse_x = 640;
}
if (SDL_abs(y) > (MOUSE_DEADZONE * 32768) / 100)
{
mouse_y += (y * MOUSE_SENSITIVITY) / 32768;
if (mouse_y < 0)
mouse_y = 0;
if (mouse_y > 640)
mouse_y = 640;
}
data->point.x = (int16_t)mouse_x;
data->point.y = (int16_t)mouse_y;
}
}
static void keypad_read(lv_indev_drv_t *indev_drv_gamepad, lv_indev_data_t *data)
{
data->key = 0;
static SDL_Event e;
if (SDL_PollEvent(&e))
{
if (e.type == SDL_WINDOWEVENT)
{
if (e.window.event == SDL_WINDOWEVENT_CLOSE)
{
quit_event = true;
}
}
// Handle controller hotplugging
if (e.type == SDL_CONTROLLERDEVICEADDED)
{
SDL_GameController *new_pad = SDL_GameControllerOpen(e.cdevice.which);
if (pad == NULL)
{
pad = new_pad;
}
}
if (e.type == SDL_CONTROLLERDEVICEREMOVED)
{
if (pad == SDL_GameControllerFromInstanceID(e.cdevice.which))
{
pad = NULL;
}
SDL_GameControllerClose(SDL_GameControllerFromInstanceID(e.cdevice.which));
}
// Parse some mouse events while we are here.
if (e.type == SDL_MOUSEMOTION || e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP)
{
mouse_event = true;
}
if ((e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP) && e.button.button == SDL_BUTTON_LEFT)
{
mouse_event = true;
mouse_pressed = (e.type == SDL_MOUSEBUTTONDOWN);
}
if ((e.type == SDL_CONTROLLERBUTTONDOWN || e.type == SDL_CONTROLLERBUTTONUP) && e.cbutton.button == SDL_CONTROLLER_BUTTON_LEFTSTICK)
{
mouse_pressed = (e.type == SDL_CONTROLLERBUTTONDOWN);
}
// Handle controller button events
if (e.type == SDL_CONTROLLERBUTTONDOWN || e.type == SDL_CONTROLLERBUTTONUP)
{
// If we hit this assert, lvgl_gamecontroller_map isnt right
LV_ASSERT(lvgl_gamecontroller_map[e.cbutton.button].sdl_map == e.cbutton.button);
data->key = lvgl_gamecontroller_map[e.cbutton.button].lvgl_map;
data->state = (e.type == SDL_CONTROLLERBUTTONDOWN) ? LV_INDEV_STATE_PRESSED : LV_INDEV_STATE_RELEASED;
}
if (e.type == SDL_CONTROLLERAXISMOTION && e.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERLEFT)
{
static bool pressed = 0;
data->key = 'L';
if (e.caxis.value > 0x20 && pressed == 0)
{
data->key = 'L';
data->state = LV_INDEV_STATE_PRESSED;
pressed = 1;
}
else if (e.caxis.value < 0x10 && pressed == 1)
{
data->key = 'L';
data->state = LV_INDEV_STATE_RELEASED;
pressed = 0;
}
}
if (e.type == SDL_CONTROLLERAXISMOTION && e.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT)
{
static bool pressed = 0;
data->key = 'R';
if (e.caxis.value > 0x20 && pressed == 0)
{
data->key = 'R';
data->state = LV_INDEV_STATE_PRESSED;
pressed = 1;
}
else if (e.caxis.value < 0x10 && pressed == 1)
{
data->key = 'R';
data->state = LV_INDEV_STATE_RELEASED;
pressed = 0;
}
}
// Handle keyboard button events
if (e.type == SDL_KEYDOWN || e.type == SDL_KEYUP)
{
for (int i = 0; i < (sizeof(lvgl_keyboard_map) / sizeof(keyboard_map_t)); i++)
{
if (lvgl_keyboard_map[i].sdl_map == e.key.keysym.sym)
{
data->key = lvgl_keyboard_map[i].lvgl_map;
data->state = (e.type == SDL_KEYUP) ? LV_INDEV_STATE_PRESSED : LV_INDEV_STATE_RELEASED;
}
}
}
}
//Is there more input events?
data->continue_reading = (SDL_PollEvent(NULL) != 0);
}
void lv_port_indev_init(bool use_mouse_cursor)
{
SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);
for (int i = 0; i < SDL_NumJoysticks(); i++)
{
SDL_GameControllerOpen(i);
}
// Register the gamepad as a keypad
lv_indev_drv_init(&indev_drv_gamepad);
indev_drv_gamepad.type = LV_INDEV_TYPE_KEYPAD;
indev_drv_gamepad.read_cb = keypad_read;
indev_keypad = lv_indev_drv_register(&indev_drv_gamepad);
// Register a mouse cursor
if (use_mouse_cursor)
{
lv_indev_drv_init(&indev_drv_mouse);
indev_drv_mouse.type = LV_INDEV_TYPE_POINTER;
indev_drv_mouse.read_cb = mouse_read;
indev_mouse = lv_indev_drv_register(&indev_drv_mouse);
mouse_cursor = lv_img_create(lv_scr_act());
lv_img_set_src(mouse_cursor, LV_SYMBOL_PLUS);
lv_indev_set_cursor(indev_mouse, mouse_cursor);
}
quit_event = false;
}
void lv_port_indev_deinit(void)
{
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
}
|
0 | repos/zig_workbench/BaseLVGL/lib | repos/zig_workbench/BaseLVGL/lib/lvgl_drv/lv_xbox_disp.c | //SPDX-License-Identifier: MIT
#ifdef NXDK
#include <assert.h>
#include <hal/video.h>
#include "lv_port_disp.h"
#include "lvgl.h"
static void *fb1, *fb2;
static lv_disp_drv_t disp_drv;
static lv_disp_draw_buf_t draw_buf;
static int DISPLAY_WIDTH;
static int DISPLAY_HEIGHT;
static void disp_flush(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p)
{
VIDEOREG(0x00600800) = (unsigned int)MmGetPhysicalAddress(color_p);
XVideoFlushFB();
lv_disp_flush_ready(disp_drv);
}
void lv_port_disp_init(int width, int height)
{
DISPLAY_WIDTH = width;
DISPLAY_HEIGHT = height;
XVideoSetMode(DISPLAY_WIDTH, DISPLAY_HEIGHT, LV_COLOR_DEPTH, REFRESH_DEFAULT);
fb1 = MmAllocateContiguousMemoryEx(DISPLAY_WIDTH * DISPLAY_HEIGHT * ((LV_COLOR_DEPTH + 7) / 8),
0x00000000, 0x7FFFFFFF,
0x1000,
PAGE_READWRITE |
PAGE_WRITECOMBINE);
fb2 = MmAllocateContiguousMemoryEx(DISPLAY_WIDTH * DISPLAY_HEIGHT * ((LV_COLOR_DEPTH + 7) / 8),
0x00000000, 0x7FFFFFFF,
0x1000,
PAGE_READWRITE |
PAGE_WRITECOMBINE);
assert(fb1 != NULL);
assert(fb2 != NULL);
RtlZeroMemory(fb1, DISPLAY_WIDTH * DISPLAY_HEIGHT * ((LV_COLOR_DEPTH + 7) / 8));
RtlZeroMemory(fb2, DISPLAY_WIDTH * DISPLAY_HEIGHT * ((LV_COLOR_DEPTH + 7) / 8));
VIDEOREG(0x00600800) = (unsigned int)MmGetPhysicalAddress(fb1);
XVideoFlushFB();
lv_disp_draw_buf_init(&draw_buf, fb1, fb2, DISPLAY_WIDTH * DISPLAY_HEIGHT);
lv_disp_drv_init(&disp_drv);
disp_drv.hor_res = DISPLAY_WIDTH;
disp_drv.ver_res = DISPLAY_HEIGHT;
disp_drv.flush_cb = disp_flush;
disp_drv.draw_buf = &draw_buf;
disp_drv.full_refresh = 1;
lv_disp_drv_register(&disp_drv);
}
void lv_port_disp_deinit()
{
MmFreeContiguousMemory(fb1);
MmFreeContiguousMemory(fb2);
}
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib | repos/zig_workbench/BaseLVGL/lib/lvgl_drv/win32drv.h | /**
* @file win32drv.h
*
*/
#ifndef LV_WIN32DRV_H
#define LV_WIN32DRV_H
/*********************
* INCLUDES
*********************/
#include "../lvgl/lvgl.h"
#include "../lvgl/src/display/lv_display.h"
#include "../lvgl/src/misc/lv_color.h"
#include <windows.h>
#if _MSC_VER >= 1200
// Disable compilation warnings.
#pragma warning(push)
// nonstandard extension used : bit field types other than int
#pragma warning(disable:4214)
// 'conversion' conversion from 'type1' to 'type2', possible loss of data
#pragma warning(disable:4244)
#endif
#ifdef LV_LVGL_H_INCLUDE_SIMPLE
#include "lvgl.h"
#else
#include "../lvgl/lvgl.h"
#endif
#if _MSC_VER >= 1200
// Restore compilation warnings.
#pragma warning(pop)
#endif
/*********************
* DEFINES
*********************/
#define LVGL_SIMULATOR_WINDOW_CLASS L"BaseLVGL"
/**********************
* TYPEDEFS
**********************/
typedef struct _lv_win32_keyboard_queue_item_t
{
SLIST_ENTRY ItemEntry;
uint32_t key;
lv_indev_state_t state;
} lv_win32_keyboard_queue_item_t;
typedef struct _lv_win32_window_context_t
{
lv_disp_t* display_device_object;
lv_indev_t* mouse_device_object;
lv_indev_t* mousewheel_device_object;
lv_indev_t* keyboard_device_object;
int32_t display_hor_res;
int32_t display_ver_res;
uint32_t display_dpi;
void* display_draw_buffer_base;
size_t display_draw_buffer_size;
volatile bool display_refreshing;
HDC display_framebuffer_context_handle;
uint32_t* display_framebuffer_base;
size_t display_framebuffer_size;
lv_indev_state_t mouse_state;
lv_point_t mouse_point;
lv_indev_state_t mousewheel_state;
int16_t mousewheel_enc_diff;
CRITICAL_SECTION keyboard_mutex;
PSLIST_HEADER keyboard_queue;
uint16_t keyboard_utf16_high_surrogate;
uint16_t keyboard_utf16_low_surrogate;
} lv_win32_window_context_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
EXTERN_C bool lv_win32_quit_signal;
EXTERN_C lv_indev_t* lv_win32_pointer_device_object;
EXTERN_C lv_indev_t* lv_win32_keypad_device_object;
EXTERN_C lv_indev_t* lv_win32_encoder_device_object;
EXTERN_C void lv_win32_add_all_input_devices_to_group(
lv_group_t* group);
EXTERN_C lv_win32_window_context_t* lv_win32_get_window_context(
HWND window_handle);
EXTERN_C bool lv_win32_init_window_class();
EXTERN_C HWND lv_win32_create_display_window(
const wchar_t* window_title,
int32_t hor_res,
int32_t ver_res,
HINSTANCE instance_handle,
HICON icon_handle,
int show_window_mode);
EXTERN_C bool lv_win32_init(
HINSTANCE instance_handle,
int show_window_mode,
int32_t hor_res,
int32_t ver_res,
HICON icon_handle);
/**********************
* MACROS
**********************/
#endif /*LV_WIN32DRV_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib | repos/zig_workbench/BaseLVGL/lib/lvgl_drv/lv_sdl_disp.c | //SPDX-License-Identifier: MIT
#include <assert.h>
#include <SDL.h>
#include "lv_port_disp.h"
#include "lvgl.h"
static void *fb1, *fb2;
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
SDL_Texture *texture = NULL;
static lv_disp_drv_t disp_drv;
static lv_disp_draw_buf_t draw_buf;
static int DISPLAY_WIDTH;
static int DISPLAY_HEIGHT;
#ifndef WINDOW_NAME
#define WINDOW_NAME "LVGL"
#endif
static void disp_flush(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p)
{
SDL_Rect r;
r.x = area->x1;
r.y = area->y1;
r.w = area->x2 - area->x1 + 1;
r.h = area->y2 - area->y1 + 1;
SDL_UpdateTexture(texture, &r, color_p, r.w * ((LV_COLOR_DEPTH + 7) / 8));
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
lv_disp_flush_ready(disp_drv);
}
void lv_port_disp_init(int width, int height)
{
assert(LV_COLOR_DEPTH == 16 || LV_COLOR_DEPTH == 32);
DISPLAY_WIDTH = width;
DISPLAY_HEIGHT = height;
SDL_InitSubSystem(SDL_INIT_VIDEO);
window = SDL_CreateWindow(WINDOW_NAME,
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
DISPLAY_WIDTH, DISPLAY_HEIGHT, 0);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE);
texture = SDL_CreateTexture(renderer,
(LV_COLOR_DEPTH == 32) ? (SDL_PIXELFORMAT_ARGB8888) : (SDL_PIXELFORMAT_RGB565),
SDL_TEXTUREACCESS_STREAMING,
DISPLAY_WIDTH,
DISPLAY_HEIGHT);
fb1 = malloc(DISPLAY_WIDTH * DISPLAY_HEIGHT * ((LV_COLOR_DEPTH + 7) / 8));
fb2 = malloc(DISPLAY_WIDTH * DISPLAY_HEIGHT * ((LV_COLOR_DEPTH + 7) / 8));
lv_disp_draw_buf_init(&draw_buf, fb1, fb2, DISPLAY_WIDTH * DISPLAY_HEIGHT);
lv_disp_drv_init(&disp_drv);
disp_drv.hor_res = DISPLAY_WIDTH;
disp_drv.ver_res = DISPLAY_HEIGHT;
disp_drv.flush_cb = disp_flush;
disp_drv.draw_buf = &draw_buf;
disp_drv.full_refresh = 1;
lv_disp_drv_register(&disp_drv);
}
void lv_port_disp_deinit()
{
free(fb1);
free(fb2);
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_QuitSubSystem(SDL_INIT_VIDEO);
}
|
0 | repos/zig_workbench/BaseLVGL/lib | repos/zig_workbench/BaseLVGL/lib/lvgl_drv/win32drv.c | /**
* @file win32drv.c
*
*/
/*********************
* INCLUDES
*********************/
#include "win32drv.h"
#include <windowsx.h>
#include <malloc.h>
#include <process.h>
#include <stdbool.h>
#include <stdint.h>
/*********************
* DEFINES
*********************/
#define WINDOW_EX_STYLE \
WS_EX_CLIENTEDGE
#define WINDOW_STYLE \
(WS_OVERLAPPEDWINDOW & ~(WS_SIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME))
#ifndef WIN32DRV_MONITOR_ZOOM
#define WIN32DRV_MONITOR_ZOOM 1
#endif
#ifndef USER_DEFAULT_SCREEN_DPI
#define USER_DEFAULT_SCREEN_DPI 96
#endif
/**********************
* TYPEDEFS
**********************/
typedef struct _WINDOW_THREAD_PARAMETER
{
HANDLE window_mutex;
HINSTANCE instance_handle;
HICON icon_handle;
int32_t hor_res;
int32_t ver_res;
int show_window_mode;
} WINDOW_THREAD_PARAMETER, * PWINDOW_THREAD_PARAMETER;
/**********************
* STATIC PROTOTYPES
**********************/
/**
* @brief Creates a B8G8R8A8 frame buffer.
* @param WindowHandle A handle to the window for the creation of the frame
* buffer. If this value is NULL, the entire screen will be
* referenced.
* @param Width The width of the frame buffer.
* @param Height The height of the frame buffer.
* @param PixelBuffer The raw pixel buffer of the frame buffer you created.
* @param PixelBufferSize The size of the frame buffer you created.
* @return If the function succeeds, the return value is a handle to the device
* context (DC) for the frame buffer. If the function fails, the return
* value is NULL, and PixelBuffer parameter is NULL.
*/
static HDC lv_win32_create_frame_buffer(
_In_opt_ HWND WindowHandle,
_In_ LONG Width,
_In_ LONG Height,
_Out_ UINT32** PixelBuffer,
_Out_ SIZE_T* PixelBufferSize);
/**
* @brief Enables WM_DPICHANGED message for child window for the associated
* window.
* @param WindowHandle The window you want to enable WM_DPICHANGED message for
* child window.
* @return If the function succeeds, the return value is non-zero. If the
* function fails, the return value is zero.
* @remarks You need to use this function in Windows 10 Threshold 1 or Windows
* 10 Threshold 2.
*/
static BOOL lv_win32_enable_child_window_dpi_message(
_In_ HWND WindowHandle);
/**
* @brief Registers a window as being touch-capable.
* @param hWnd The handle of the window being registered.
* @param ulFlags A set of bit flags that specify optional modifications.
* @return If the function succeeds, the return value is nonzero. If the
* function fails, the return value is zero.
* @remark For more information, see RegisterTouchWindow.
*/
static BOOL lv_win32_register_touch_window(
HWND hWnd,
ULONG ulFlags);
/**
* @brief Retrieves detailed information about touch inputs associated with a
* particular touch input handle.
* @param hTouchInput The touch input handle received in the LPARAM of a touch
* message.
* @param cInputs The number of structures in the pInputs array.
* @param pInputs A pointer to an array of TOUCHINPUT structures to receive
* information about the touch points associated with the
* specified touch input handle.
* @param cbSize The size, in bytes, of a single TOUCHINPUT structure.
* @return If the function succeeds, the return value is nonzero. If the
* function fails, the return value is zero.
* @remark For more information, see GetTouchInputInfo.
*/
static BOOL lv_win32_get_touch_input_info(
HTOUCHINPUT hTouchInput,
UINT cInputs,
PTOUCHINPUT pInputs,
int cbSize);
/**
* @brief Closes a touch input handle, frees process memory associated with it,
and invalidates the handle.
* @param hTouchInput The touch input handle received in the LPARAM of a touch
* message.
* @return If the function succeeds, the return value is nonzero. If the
* function fails, the return value is zero.
* @remark For more information, see CloseTouchInputHandle.
*/
static BOOL lv_win32_close_touch_input_handle(
HTOUCHINPUT hTouchInput);
/**
* @brief Returns the dots per inch (dpi) value for the associated window.
* @param WindowHandle The window you want to get information about.
* @return The DPI for the window.
*/
static UINT lv_win32_get_dpi_for_window(
_In_ HWND WindowHandle);
static void lv_win32_display_driver_flush_callback(
lv_disp_t* disp_drv,
const lv_area_t* area,
uint8_t* px_map);
static void lv_win32_pointer_driver_read_callback(
lv_indev_t* indev,
lv_indev_data_t* data);
static void lv_win32_keypad_driver_read_callback(
lv_indev_t* indev,
lv_indev_data_t* data);
static void lv_win32_encoder_driver_read_callback(
lv_indev_t* indev,
lv_indev_data_t* data);
static lv_win32_window_context_t* lv_win32_get_display_context(
lv_disp_t* display);
static LRESULT CALLBACK lv_win32_window_message_callback(
HWND hWnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam);
static unsigned int __stdcall lv_win32_window_thread_entrypoint(
void* raw_parameter);
static void lv_win32_push_key_to_keyboard_queue(
lv_win32_window_context_t* context,
uint32_t key,
lv_indev_state_t state)
{
lv_win32_keyboard_queue_item_t* current =
(lv_win32_keyboard_queue_item_t*)(_aligned_malloc(
sizeof(lv_win32_keyboard_queue_item_t),
MEMORY_ALLOCATION_ALIGNMENT));
if (current)
{
current->key = key;
current->state = state;
InterlockedPushEntrySList(
context->keyboard_queue,
¤t->ItemEntry);
}
}
/**********************
* GLOBAL VARIABLES
**********************/
EXTERN_C bool lv_win32_quit_signal = false;
EXTERN_C lv_indev_t* lv_win32_pointer_device_object = NULL;
EXTERN_C lv_indev_t* lv_win32_keypad_device_object = NULL;
EXTERN_C lv_indev_t* lv_win32_encoder_device_object = NULL;
/**********************
* STATIC VARIABLES
**********************/
static HWND g_window_handle = NULL;
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
EXTERN_C void lv_win32_add_all_input_devices_to_group(
lv_group_t* group)
{
if (!group)
{
LV_LOG_WARN(
"The group object is NULL. Get the default group object instead.");
group = lv_group_get_default();
if (!group)
{
LV_LOG_WARN(
"The default group object is NULL. Create a new group object "
"and set it to default instead.");
group = lv_group_create();
if (group)
{
lv_group_set_default(group);
}
}
}
LV_ASSERT_MSG(group, "Cannot obtain an available group object.");
lv_indev_set_group(lv_win32_pointer_device_object, group);
lv_indev_set_group(lv_win32_keypad_device_object, group);
lv_indev_set_group(lv_win32_encoder_device_object, group);
}
EXTERN_C lv_win32_window_context_t* lv_win32_get_window_context(
HWND window_handle)
{
return (lv_win32_window_context_t*)(
GetPropW(window_handle, L"LVGL.SimulatorWindow.WindowContext"));
}
EXTERN_C bool lv_win32_init_window_class()
{
WNDCLASSEXW window_class;
window_class.cbSize = sizeof(WNDCLASSEXW);
window_class.style = 0;
window_class.lpfnWndProc = lv_win32_window_message_callback;
window_class.cbClsExtra = 0;
window_class.cbWndExtra = 0;
window_class.hInstance = NULL;
window_class.hIcon = NULL;
window_class.hCursor = LoadCursorW(NULL, IDC_ARROW);
window_class.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
window_class.lpszMenuName = NULL;
window_class.lpszClassName = LVGL_SIMULATOR_WINDOW_CLASS;
window_class.hIconSm = NULL;
return RegisterClassExW(&window_class);
}
EXTERN_C HWND lv_win32_create_display_window(
const wchar_t* window_title,
int32_t hor_res,
int32_t ver_res,
HINSTANCE instance_handle,
HICON icon_handle,
int show_window_mode)
{
HWND display_window_handle = CreateWindowExW(
WINDOW_EX_STYLE,
LVGL_SIMULATOR_WINDOW_CLASS,
window_title,
WINDOW_STYLE,
CW_USEDEFAULT,
0,
hor_res,
ver_res,
NULL,
NULL,
instance_handle,
NULL);
if (display_window_handle)
{
SendMessageW(
display_window_handle,
WM_SETICON,
TRUE,
(LPARAM)icon_handle);
SendMessageW(
display_window_handle,
WM_SETICON,
FALSE,
(LPARAM)icon_handle);
ShowWindow(display_window_handle, show_window_mode);
UpdateWindow(display_window_handle);
}
return display_window_handle;
}
EXTERN_C bool lv_win32_init(
HINSTANCE instance_handle,
int show_window_mode,
int32_t hor_res,
int32_t ver_res,
HICON icon_handle)
{
if (!lv_win32_init_window_class())
{
return false;
}
PWINDOW_THREAD_PARAMETER parameter =
(PWINDOW_THREAD_PARAMETER)malloc(sizeof(WINDOW_THREAD_PARAMETER));
parameter->window_mutex = CreateEventExW(NULL, NULL, 0, EVENT_ALL_ACCESS);
parameter->instance_handle = instance_handle;
parameter->icon_handle = icon_handle;
parameter->hor_res = hor_res;
parameter->ver_res = ver_res;
parameter->show_window_mode = show_window_mode;
_beginthreadex(
NULL,
0,
lv_win32_window_thread_entrypoint,
parameter,
0,
NULL);
WaitForSingleObjectEx(parameter->window_mutex, INFINITE, FALSE);
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
lv_win32_get_window_context(g_window_handle));
if (!context)
{
return false;
}
lv_win32_pointer_device_object = context->mouse_device_object;
lv_win32_keypad_device_object = context->keyboard_device_object;
lv_win32_encoder_device_object = context->mousewheel_device_object;
return true;
}
/**********************
* STATIC FUNCTIONS
**********************/
static HDC lv_win32_create_frame_buffer(
HWND WindowHandle,
LONG Width,
LONG Height,
UINT32** PixelBuffer,
SIZE_T* PixelBufferSize)
{
HDC hFrameBufferDC = NULL;
if (PixelBuffer && PixelBufferSize)
{
HDC hWindowDC = GetDC(WindowHandle);
if (hWindowDC)
{
hFrameBufferDC = CreateCompatibleDC(hWindowDC);
ReleaseDC(WindowHandle, hWindowDC);
}
if (hFrameBufferDC)
{
#if LV_COLOR_DEPTH == 32
BITMAPINFO BitmapInfo = { 0 };
#elif LV_COLOR_DEPTH == 16
typedef struct _BITMAPINFO_16BPP {
BITMAPINFOHEADER bmiHeader;
DWORD bmiColorMask[3];
} BITMAPINFO_16BPP, *PBITMAPINFO_16BPP;
BITMAPINFO_16BPP BitmapInfo = { 0 };
#elif LV_COLOR_DEPTH == 8
typedef struct _BITMAPINFO_8BPP {
BITMAPINFOHEADER bmiHeader;
RGBQUAD bmiColors[256];
} BITMAPINFO_8BPP, *PBITMAPINFO_8BPP;
BITMAPINFO_8BPP BitmapInfo = { 0 };
#elif LV_COLOR_DEPTH == 1
typedef struct _BITMAPINFO_1BPP {
BITMAPINFOHEADER bmiHeader;
RGBQUAD bmiColors[2];
} BITMAPINFO_1BPP, *PBITMAPINFO_1BPP;
BITMAPINFO_1BPP BitmapInfo = { 0 };
#else
BITMAPINFO BitmapInfo = { 0 };
#endif
BitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
BitmapInfo.bmiHeader.biWidth = Width;
BitmapInfo.bmiHeader.biHeight = -Height;
BitmapInfo.bmiHeader.biPlanes = 1;
#if LV_COLOR_DEPTH == 32
BitmapInfo.bmiHeader.biBitCount = 32;
BitmapInfo.bmiHeader.biCompression = BI_RGB;
#elif LV_COLOR_DEPTH == 16
BitmapInfo.bmiHeader.biBitCount = 16;
BitmapInfo.bmiHeader.biCompression = BI_BITFIELDS;
BitmapInfo.bmiColorMask[0] = 0xF800;
BitmapInfo.bmiColorMask[1] = 0x07E0;
BitmapInfo.bmiColorMask[2] = 0x001F;
#elif LV_COLOR_DEPTH == 8
BitmapInfo.bmiHeader.biBitCount = 8;
BitmapInfo.bmiHeader.biCompression = BI_RGB;
for (size_t i = 0; i < 256; ++i)
{
lv_color8_t color;
color.full = i;
BitmapInfo.bmiColors[i].rgbRed = LV_COLOR_GET_R(color) * 36;
BitmapInfo.bmiColors[i].rgbGreen = LV_COLOR_GET_G(color) * 36;
BitmapInfo.bmiColors[i].rgbBlue = LV_COLOR_GET_B(color) * 85;
BitmapInfo.bmiColors[i].rgbReserved = 0xFF;
}
#elif LV_COLOR_DEPTH == 1
BitmapInfo.bmiHeader.biBitCount = 8;
BitmapInfo.bmiHeader.biCompression = BI_RGB;
BitmapInfo.bmiHeader.biClrUsed = 2;
BitmapInfo.bmiHeader.biClrImportant = 2;
BitmapInfo.bmiColors[0].rgbRed = 0x00;
BitmapInfo.bmiColors[0].rgbGreen = 0x00;
BitmapInfo.bmiColors[0].rgbBlue = 0x00;
BitmapInfo.bmiColors[0].rgbReserved = 0xFF;
BitmapInfo.bmiColors[1].rgbRed = 0xFF;
BitmapInfo.bmiColors[1].rgbGreen = 0xFF;
BitmapInfo.bmiColors[1].rgbBlue = 0xFF;
BitmapInfo.bmiColors[1].rgbReserved = 0xFF;
#else
BitmapInfo.bmiHeader.biBitCount = 32;
BitmapInfo.bmiHeader.biCompression = BI_RGB;
#endif
HBITMAP hBitmap = CreateDIBSection(
hFrameBufferDC,
(PBITMAPINFO)(&BitmapInfo),
DIB_RGB_COLORS,
(void**)PixelBuffer,
NULL,
0);
if (hBitmap)
{
#if LV_COLOR_DEPTH == 32
*PixelBufferSize = Width * Height * sizeof(UINT32);
#elif LV_COLOR_DEPTH == 16
*PixelBufferSize = Width * Height * sizeof(UINT16);
#elif LV_COLOR_DEPTH == 8
*PixelBufferSize = Width * Height * sizeof(UINT8);
#elif LV_COLOR_DEPTH == 1
*PixelBufferSize = Width * Height * sizeof(UINT8);
#else
*PixelBufferSize = Width * Height * sizeof(UINT32);
#endif
DeleteObject(SelectObject(hFrameBufferDC, hBitmap));
DeleteObject(hBitmap);
}
else
{
DeleteDC(hFrameBufferDC);
hFrameBufferDC = NULL;
}
}
}
return hFrameBufferDC;
}
static BOOL lv_win32_enable_child_window_dpi_message(
HWND WindowHandle)
{
// This hack is only for Windows 10 TH1/TH2 only.
// We don't need this hack if the Per Monitor Aware V2 is existed.
OSVERSIONINFOEXW OSVersionInfoEx = { 0 };
OSVersionInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
OSVersionInfoEx.dwMajorVersion = 10;
OSVersionInfoEx.dwMinorVersion = 0;
OSVersionInfoEx.dwBuildNumber = 14393;
if (!VerifyVersionInfoW(
&OSVersionInfoEx,
VER_MAJORVERSION | VER_MINORVERSION | VER_BUILDNUMBER,
VerSetConditionMask(
VerSetConditionMask(
VerSetConditionMask(
0,
VER_MAJORVERSION,
VER_GREATER_EQUAL),
VER_MINORVERSION,
VER_GREATER_EQUAL),
VER_BUILDNUMBER,
VER_LESS)))
{
return FALSE;
}
HMODULE ModuleHandle = GetModuleHandleW(L"user32.dll");
if (!ModuleHandle)
{
return FALSE;
}
typedef BOOL(WINAPI* FunctionType)(HWND, BOOL);
FunctionType pFunction = (FunctionType)(
GetProcAddress(ModuleHandle, "EnableChildWindowDpiMessage"));
if (!pFunction)
{
return FALSE;
}
return pFunction(WindowHandle, TRUE);
}
static BOOL lv_win32_register_touch_window(
HWND hWnd,
ULONG ulFlags)
{
HMODULE ModuleHandle = GetModuleHandleW(L"user32.dll");
if (!ModuleHandle)
{
return FALSE;
}
typedef BOOL(WINAPI* FunctionType)(HWND, ULONG);
FunctionType pFunction = (FunctionType)(
GetProcAddress(ModuleHandle, "RegisterTouchWindow"));
if (!pFunction)
{
return FALSE;
}
return pFunction(hWnd, ulFlags);
}
static BOOL lv_win32_get_touch_input_info(
HTOUCHINPUT hTouchInput,
UINT cInputs,
PTOUCHINPUT pInputs,
int cbSize)
{
HMODULE ModuleHandle = GetModuleHandleW(L"user32.dll");
if (!ModuleHandle)
{
return FALSE;
}
typedef BOOL(WINAPI* FunctionType)(HTOUCHINPUT, UINT, PTOUCHINPUT, int);
FunctionType pFunction = (FunctionType)(
GetProcAddress(ModuleHandle, "GetTouchInputInfo"));
if (!pFunction)
{
return FALSE;
}
return pFunction(hTouchInput, cInputs, pInputs, cbSize);
}
static BOOL lv_win32_close_touch_input_handle(
HTOUCHINPUT hTouchInput)
{
HMODULE ModuleHandle = GetModuleHandleW(L"user32.dll");
if (!ModuleHandle)
{
return FALSE;
}
typedef BOOL(WINAPI* FunctionType)(HTOUCHINPUT);
FunctionType pFunction = (FunctionType)(
GetProcAddress(ModuleHandle, "CloseTouchInputHandle"));
if (!pFunction)
{
return FALSE;
}
return pFunction(hTouchInput);
}
static UINT lv_win32_get_dpi_for_window(
_In_ HWND WindowHandle)
{
UINT Result = (UINT)(-1);
HMODULE ModuleHandle = LoadLibraryW(L"SHCore.dll");
if (ModuleHandle)
{
typedef enum MONITOR_DPI_TYPE_PRIVATE {
MDT_EFFECTIVE_DPI = 0,
MDT_ANGULAR_DPI = 1,
MDT_RAW_DPI = 2,
MDT_DEFAULT = MDT_EFFECTIVE_DPI
} MONITOR_DPI_TYPE_PRIVATE;
typedef HRESULT(WINAPI* FunctionType)(
HMONITOR, MONITOR_DPI_TYPE_PRIVATE, UINT*, UINT*);
FunctionType pFunction = (FunctionType)(
GetProcAddress(ModuleHandle, "GetDpiForMonitor"));
if (pFunction)
{
HMONITOR MonitorHandle = MonitorFromWindow(
WindowHandle,
MONITOR_DEFAULTTONEAREST);
UINT dpiX = 0;
UINT dpiY = 0;
if (SUCCEEDED(pFunction(
MonitorHandle,
MDT_EFFECTIVE_DPI,
&dpiX,
&dpiY)))
{
Result = dpiX;
}
}
FreeLibrary(ModuleHandle);
}
if (Result == (UINT)(-1))
{
HDC hWindowDC = GetDC(WindowHandle);
if (hWindowDC)
{
Result = GetDeviceCaps(hWindowDC, LOGPIXELSX);
ReleaseDC(WindowHandle, hWindowDC);
}
}
if (Result == (UINT)(-1))
{
Result = USER_DEFAULT_SCREEN_DPI;
}
return Result;
}
static void lv_win32_display_driver_flush_callback(
lv_disp_t* disp_drv,
const lv_area_t* area,
uint8_t* px_map)
{
HWND window_handle = (HWND)lv_display_get_user_data(disp_drv);
if (!window_handle)
{
lv_display_flush_ready(disp_drv);
return;
}
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
lv_win32_get_window_context(window_handle));
if (!context)
{
lv_display_flush_ready(disp_drv);
return;
}
if (lv_display_flush_is_last(disp_drv) && !context->display_refreshing)
{
#if (LV_COLOR_DEPTH == 32) || \
(LV_COLOR_DEPTH == 16 && LV_COLOR_16_SWAP == 0) || \
(LV_COLOR_DEPTH == 8) || \
(LV_COLOR_DEPTH == 1)
UNREFERENCED_PARAMETER(px_map);
memcpy(
context->display_framebuffer_base,
context->display_draw_buffer_base,
context->display_draw_buffer_size);
#elif (LV_COLOR_DEPTH == 16 && LV_COLOR_16_SWAP != 0)
SIZE_T count = context->display_framebuffer_size / sizeof(UINT16);
PUINT16 source = (PUINT16)px_map;
PUINT16 destination = (PUINT16)context->display_framebuffer_base;
for (SIZE_T i = 0; i < count; ++i)
{
UINT16 current = *source;
*destination = (LOBYTE(current) << 8) | HIBYTE(current);
++source;
++destination;
}
#else
uint32_t* destination = context->display_framebuffer_base;
for (int y = area->y1; y <= area->y2; ++y)
{
for (int x = area->x1; x <= area->x2; ++x)
{
destination[y * context->display_hor_res + x] =
lv_color_to32(*px_map);
px_map++;
}
}
#endif
context->display_refreshing = true;
InvalidateRect(window_handle, NULL, FALSE);
}
lv_display_flush_ready(disp_drv);
}
static void lv_win32_pointer_driver_read_callback(
lv_indev_t* indev,
lv_indev_data_t* data)
{
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
lv_win32_get_display_context(lv_indev_get_disp(indev)));
if (!context)
{
return;
}
data->state = context->mouse_state;
data->point = context->mouse_point;
}
static void lv_win32_keypad_driver_read_callback(
lv_indev_t* indev,
lv_indev_data_t* data)
{
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
lv_win32_get_display_context(lv_indev_get_disp(indev)));
if (!context)
{
return;
}
EnterCriticalSection(&context->keyboard_mutex);
lv_win32_keyboard_queue_item_t* current =
(lv_win32_keyboard_queue_item_t*)(InterlockedPopEntrySList(
context->keyboard_queue));
if (current)
{
data->key = current->key;
data->state = current->state;
_aligned_free(current);
data->continue_reading = true;
}
LeaveCriticalSection(&context->keyboard_mutex);
}
static void lv_win32_encoder_driver_read_callback(
lv_indev_t* indev,
lv_indev_data_t* data)
{
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
lv_win32_get_display_context(lv_indev_get_disp(indev)));
if (!context)
{
return;
}
data->state = context->mousewheel_state;
data->enc_diff = context->mousewheel_enc_diff;
context->mousewheel_enc_diff = 0;
}
static lv_win32_window_context_t* lv_win32_get_display_context(
lv_disp_t* display)
{
if (display)
{
return lv_win32_get_window_context(
(HWND)lv_disp_get_user_data(display));
}
return NULL;
}
static LRESULT CALLBACK lv_win32_window_message_callback(
HWND hWnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
switch (uMsg)
{
case WM_CREATE:
{
// Note: Return -1 directly because WM_DESTROY message will be sent
// when destroy the window automatically. We free the resource when
// processing the WM_DESTROY message of this window.
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
malloc(sizeof(lv_win32_window_context_t)));
if (!context)
{
return -1;
}
RECT request_content_size;
GetWindowRect(hWnd, &request_content_size);
context->display_hor_res =
request_content_size.right - request_content_size.left;
context->display_ver_res =
request_content_size.bottom - request_content_size.top;
context->display_dpi = lv_win32_get_dpi_for_window(hWnd);
context->display_refreshing = true;
context->display_framebuffer_context_handle =
lv_win32_create_frame_buffer(
hWnd,
context->display_hor_res,
context->display_ver_res,
&context->display_framebuffer_base,
&context->display_framebuffer_size);
context->display_device_object = lv_display_create(
context->display_hor_res,
context->display_ver_res);
if (!context->display_device_object)
{
return -1;
}
lv_display_set_flush_cb(
context->display_device_object,
lv_win32_display_driver_flush_callback);
lv_display_set_user_data(
context->display_device_object,
hWnd);
context->display_draw_buffer_size =
lv_color_format_get_size(LV_COLOR_FORMAT_NATIVE);
context->display_draw_buffer_size *= context->display_hor_res;
context->display_draw_buffer_size *= context->display_ver_res;
context->display_draw_buffer_base =
malloc(context->display_draw_buffer_size);
if (!context->display_draw_buffer_base)
{
return -1;
}
lv_display_set_draw_buffers(
context->display_device_object,
context->display_draw_buffer_base,
NULL,
context->display_draw_buffer_size,
LV_DISPLAY_RENDER_MODE_DIRECT);
context->mouse_state = LV_INDEV_STATE_RELEASED;
context->mouse_point.x = 0;
context->mouse_point.y = 0;
context->mouse_device_object = lv_indev_create();
if (!context->mouse_device_object)
{
return -1;
}
lv_indev_set_type(
context->mouse_device_object,
LV_INDEV_TYPE_POINTER);
lv_indev_set_read_cb(
context->mouse_device_object,
lv_win32_pointer_driver_read_callback);
lv_indev_set_disp(
context->mouse_device_object,
context->display_device_object);
context->mousewheel_state = LV_INDEV_STATE_RELEASED;
context->mousewheel_enc_diff = 0;
context->mousewheel_device_object = lv_indev_create();
if (!context->mousewheel_device_object)
{
return -1;
}
lv_indev_set_type(
context->mousewheel_device_object,
LV_INDEV_TYPE_ENCODER);
lv_indev_set_read_cb(
context->mousewheel_device_object,
lv_win32_encoder_driver_read_callback);
lv_indev_set_disp(
context->mousewheel_device_object,
context->display_device_object);
InitializeCriticalSection(&context->keyboard_mutex);
context->keyboard_queue = _aligned_malloc(
sizeof(SLIST_HEADER),
MEMORY_ALLOCATION_ALIGNMENT);
if (!context->keyboard_queue)
{
return -1;
}
InitializeSListHead(context->keyboard_queue);
context->keyboard_utf16_high_surrogate = 0;
context->keyboard_utf16_low_surrogate = 0;
context->keyboard_device_object = lv_indev_create();
if (!context->keyboard_device_object)
{
return -1;
}
lv_indev_set_type(
context->keyboard_device_object,
LV_INDEV_TYPE_KEYPAD);
lv_indev_set_read_cb(
context->keyboard_device_object,
lv_win32_keypad_driver_read_callback);
lv_indev_set_disp(
context->keyboard_device_object,
context->display_device_object);
if (!SetPropW(
hWnd,
L"LVGL.SimulatorWindow.WindowContext",
(HANDLE)(context)))
{
return -1;
}
RECT calculated_window_size;
calculated_window_size.left = 0;
calculated_window_size.right = MulDiv(
context->display_hor_res * WIN32DRV_MONITOR_ZOOM,
context->display_dpi,
USER_DEFAULT_SCREEN_DPI);
calculated_window_size.top = 0;
calculated_window_size.bottom = MulDiv(
context->display_ver_res * WIN32DRV_MONITOR_ZOOM,
context->display_dpi,
USER_DEFAULT_SCREEN_DPI);
AdjustWindowRectEx(
&calculated_window_size,
WINDOW_STYLE,
FALSE,
WINDOW_EX_STYLE);
OffsetRect(
&calculated_window_size,
-calculated_window_size.left,
-calculated_window_size.top);
SetWindowPos(
hWnd,
NULL,
0,
0,
calculated_window_size.right,
calculated_window_size.bottom,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE);
lv_win32_register_touch_window(hWnd, 0);
lv_win32_enable_child_window_dpi_message(hWnd);
break;
}
case WM_MOUSEMOVE:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
{
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
lv_win32_get_window_context(hWnd));
if (!context)
{
return 0;
}
context->mouse_point.x = MulDiv(
GET_X_LPARAM(lParam),
USER_DEFAULT_SCREEN_DPI,
WIN32DRV_MONITOR_ZOOM * context->display_dpi);
context->mouse_point.y = MulDiv(
GET_Y_LPARAM(lParam),
USER_DEFAULT_SCREEN_DPI,
WIN32DRV_MONITOR_ZOOM * context->display_dpi);
if (context->mouse_point.x < 0)
{
context->mouse_point.x = 0;
}
if (context->mouse_point.x > context->display_hor_res - 1)
{
context->mouse_point.x = context->display_hor_res - 1;
}
if (context->mouse_point.y < 0)
{
context->mouse_point.y = 0;
}
if (context->mouse_point.y > context->display_ver_res - 1)
{
context->mouse_point.y = context->display_ver_res - 1;
}
if (uMsg == WM_LBUTTONDOWN || uMsg == WM_LBUTTONUP)
{
context->mouse_state = (
uMsg == WM_LBUTTONDOWN
? LV_INDEV_STATE_PRESSED
: LV_INDEV_STATE_RELEASED);
}
else if (uMsg == WM_MBUTTONDOWN || uMsg == WM_MBUTTONUP)
{
context->mousewheel_state = (
uMsg == WM_MBUTTONDOWN
? LV_INDEV_STATE_PRESSED
: LV_INDEV_STATE_RELEASED);
}
return 0;
}
case WM_KEYDOWN:
case WM_KEYUP:
{
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
lv_win32_get_window_context(hWnd));
if (context)
{
EnterCriticalSection(&context->keyboard_mutex);
bool skip_translation = false;
uint32_t translated_key = 0;
switch (wParam)
{
case VK_UP:
translated_key = LV_KEY_UP;
break;
case VK_DOWN:
translated_key = LV_KEY_DOWN;
break;
case VK_LEFT:
translated_key = LV_KEY_LEFT;
break;
case VK_RIGHT:
translated_key = LV_KEY_RIGHT;
break;
case VK_ESCAPE:
translated_key = LV_KEY_ESC;
break;
case VK_DELETE:
translated_key = LV_KEY_DEL;
break;
case VK_BACK:
translated_key = LV_KEY_BACKSPACE;
break;
case VK_RETURN:
translated_key = LV_KEY_ENTER;
break;
case VK_TAB:
case VK_NEXT:
translated_key = LV_KEY_NEXT;
break;
case VK_PRIOR:
translated_key = LV_KEY_PREV;
break;
case VK_HOME:
translated_key = LV_KEY_HOME;
break;
case VK_END:
translated_key = LV_KEY_END;
break;
default:
skip_translation = true;
break;
}
if (!skip_translation)
{
lv_win32_push_key_to_keyboard_queue(
context,
translated_key,
((uMsg == WM_KEYUP)
? LV_INDEV_STATE_RELEASED
: LV_INDEV_STATE_PRESSED));
}
LeaveCriticalSection(&context->keyboard_mutex);
}
break;
}
case WM_CHAR:
{
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
lv_win32_get_window_context(hWnd));
if (context)
{
EnterCriticalSection(&context->keyboard_mutex);
uint16_t raw_code_point = (uint16_t)(wParam);
if (raw_code_point >= 0x20 && raw_code_point != 0x7F)
{
if (IS_HIGH_SURROGATE(raw_code_point))
{
context->keyboard_utf16_high_surrogate = raw_code_point;
}
else if (IS_LOW_SURROGATE(raw_code_point))
{
context->keyboard_utf16_low_surrogate = raw_code_point;
}
uint32_t code_point = raw_code_point;
if (context->keyboard_utf16_high_surrogate &&
context->keyboard_utf16_low_surrogate)
{
uint16_t high_surrogate =
context->keyboard_utf16_high_surrogate;
uint16_t low_surrogate =
context->keyboard_utf16_low_surrogate;
code_point = (low_surrogate & 0x03FF);
code_point += (((high_surrogate & 0x03FF) + 0x40) << 10);
context->keyboard_utf16_high_surrogate = 0;
context->keyboard_utf16_low_surrogate = 0;
}
uint32_t lvgl_code_point =
_lv_text_unicode_to_encoded(code_point);
lv_win32_push_key_to_keyboard_queue(
context,
lvgl_code_point,
LV_INDEV_STATE_PRESSED);
lv_win32_push_key_to_keyboard_queue(
context,
lvgl_code_point,
LV_INDEV_STATE_RELEASED);
}
LeaveCriticalSection(&context->keyboard_mutex);
}
break;
}
case WM_MOUSEWHEEL:
{
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
lv_win32_get_window_context(hWnd));
if (context)
{
context->mousewheel_enc_diff =
-(GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA);
}
break;
}
case WM_TOUCH:
{
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
lv_win32_get_window_context(hWnd));
if (context)
{
UINT cInputs = LOWORD(wParam);
HTOUCHINPUT hTouchInput = (HTOUCHINPUT)(lParam);
PTOUCHINPUT pInputs = malloc(cInputs * sizeof(TOUCHINPUT));
if (pInputs)
{
if (lv_win32_get_touch_input_info(
hTouchInput,
cInputs,
pInputs,
sizeof(TOUCHINPUT)))
{
for (UINT i = 0; i < cInputs; ++i)
{
POINT Point;
Point.x = TOUCH_COORD_TO_PIXEL(pInputs[i].x);
Point.y = TOUCH_COORD_TO_PIXEL(pInputs[i].y);
if (!ScreenToClient(hWnd, &Point))
{
continue;
}
context->mouse_point.x = MulDiv(
Point.x,
USER_DEFAULT_SCREEN_DPI,
WIN32DRV_MONITOR_ZOOM * context->display_dpi);
context->mouse_point.y = MulDiv(
Point.y,
USER_DEFAULT_SCREEN_DPI,
WIN32DRV_MONITOR_ZOOM * context->display_dpi);
DWORD MousePressedMask =
TOUCHEVENTF_MOVE | TOUCHEVENTF_DOWN;
context->mouse_state = (
pInputs[i].dwFlags & MousePressedMask
? LV_INDEV_STATE_PRESSED
: LV_INDEV_STATE_RELEASED);
}
}
free(pInputs);
}
lv_win32_close_touch_input_handle(hTouchInput);
}
break;
}
case WM_DPICHANGED:
{
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
lv_win32_get_window_context(hWnd));
if (context)
{
context->display_dpi = HIWORD(wParam);
LPRECT SuggestedRect = (LPRECT)lParam;
SetWindowPos(
hWnd,
NULL,
SuggestedRect->left,
SuggestedRect->top,
SuggestedRect->right,
SuggestedRect->bottom,
SWP_NOZORDER | SWP_NOACTIVATE);
RECT ClientRect;
GetClientRect(hWnd, &ClientRect);
int WindowWidth = MulDiv(
context->display_hor_res * WIN32DRV_MONITOR_ZOOM,
context->display_dpi,
USER_DEFAULT_SCREEN_DPI);
int WindowHeight = MulDiv(
context->display_ver_res * WIN32DRV_MONITOR_ZOOM,
context->display_dpi,
USER_DEFAULT_SCREEN_DPI);
SetWindowPos(
hWnd,
NULL,
SuggestedRect->left,
SuggestedRect->top,
SuggestedRect->right + (WindowWidth - ClientRect.right),
SuggestedRect->bottom + (WindowHeight - ClientRect.bottom),
SWP_NOZORDER | SWP_NOACTIVATE);
}
break;
}
case WM_PAINT:
{
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
lv_win32_get_window_context(hWnd));
if (context)
{
if (context->display_framebuffer_context_handle)
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
SetStretchBltMode(hdc, HALFTONE);
StretchBlt(
hdc,
ps.rcPaint.left,
ps.rcPaint.top,
ps.rcPaint.right - ps.rcPaint.left,
ps.rcPaint.bottom - ps.rcPaint.top,
context->display_framebuffer_context_handle,
0,
0,
MulDiv(
ps.rcPaint.right - ps.rcPaint.left,
USER_DEFAULT_SCREEN_DPI,
WIN32DRV_MONITOR_ZOOM * context->display_dpi),
MulDiv(
ps.rcPaint.bottom - ps.rcPaint.top,
USER_DEFAULT_SCREEN_DPI,
WIN32DRV_MONITOR_ZOOM * context->display_dpi),
SRCCOPY);
EndPaint(hWnd, &ps);
}
context->display_refreshing = false;
}
break;
}
case WM_DESTROY:
{
lv_win32_window_context_t* context = (lv_win32_window_context_t*)(
RemovePropW(hWnd, L"LVGL.SimulatorWindow.WindowContext"));
if (context)
{
lv_disp_t* display_device_object = context->display_device_object;
context->display_device_object = NULL;
lv_disp_remove(display_device_object);
free(context->display_draw_buffer_base);
DeleteDC(context->display_framebuffer_context_handle);
lv_indev_t* mouse_device_object =
context->mouse_device_object;
context->mouse_device_object = NULL;
lv_indev_delete(mouse_device_object);
lv_indev_t* mousewheel_device_object =
context->mousewheel_device_object;
context->mousewheel_device_object = NULL;
lv_indev_delete(mousewheel_device_object);
lv_indev_t* keyboard_device_object =
context->keyboard_device_object;
context->keyboard_device_object = NULL;
lv_indev_delete(keyboard_device_object);
do
{
PSLIST_ENTRY current = InterlockedPopEntrySList(
context->keyboard_queue);
if (!current)
{
_aligned_free(context->keyboard_queue);
context->keyboard_queue = NULL;
break;
}
_aligned_free(current);
} while (true);
DeleteCriticalSection(&context->keyboard_mutex);
free(context);
}
PostQuitMessage(0);
break;
}
default:
return DefWindowProcW(hWnd, uMsg, wParam, lParam);
}
return 0;
}
static unsigned int __stdcall lv_win32_window_thread_entrypoint(
void* raw_parameter)
{
PWINDOW_THREAD_PARAMETER parameter =
(PWINDOW_THREAD_PARAMETER)raw_parameter;
g_window_handle = lv_win32_create_display_window(
L"LVGL Simulator for Windows Desktop (Display 1)",
parameter->hor_res,
parameter->ver_res,
parameter->instance_handle,
parameter->icon_handle,
parameter->show_window_mode);
if (!g_window_handle)
{
return 0;
}
SetEvent(parameter->window_mutex);
MSG message;
while (GetMessageW(&message, NULL, 0, 0))
{
TranslateMessage(&message);
DispatchMessageW(&message);
}
lv_win32_quit_signal = true;
return 0;
}
|
0 | repos/zig_workbench/BaseLVGL/lib | repos/zig_workbench/BaseLVGL/lib/lvgl_drv/lv_port_indev.h |
/**
* @file lv_port_indev_templ.h
*
*/
/*Copy this file as "lv_port_indev.h" and set this value to "1" to enable content*/
#if 1
#ifndef LV_PORT_INDEV_TEMPL_H
#define LV_PORT_INDEV_TEMPL_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "lvgl.h"
#include "lvgl.h"
#ifdef NXDK
#include <SDL.h>
#else
#include <SDL2/SDL.h>
#endif
/*********************
* DEFINES
*********************/
typedef enum
{
LV_QUIT_NONE,
LV_REBOOT,
LV_SHUTDOWN,
LV_QUIT,
LV_QUIT_OTHER,
} lv_quit_event_t;
/**********************
* TYPEDEFS
**********************/
typedef struct
{
SDL_GameControllerButton sdl_map;
lv_key_t lvgl_map;
} gamecontroller_map_t;
typedef struct
{
SDL_Keycode sdl_map;
lv_key_t lvgl_map;
} keyboard_map_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
void lv_port_indev_init(bool use_mouse_cursor);
void lv_port_indev_deinit(void);
void lv_set_quit(lv_quit_event_t event);
lv_quit_event_t lv_get_quit(void);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_PORT_INDEV_TEMPL_H*/
#endif /*Disable/Enable content*/
|
0 | repos/zig_workbench/BaseLVGL/lib | repos/zig_workbench/BaseLVGL/lib/lvgl_drv/lv_port_disp.h | /**
* @file lv_port_disp_templ.h
*
*/
/*Copy this file as "lv_port_disp.h" and set this value to "1" to enable content*/
#if 1
#ifndef LV_PORT_DISP_H
#define LV_PORT_DISP_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "lvgl.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
void lv_port_disp_init(int width, int height);
void lv_port_disp_deinit(void);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_PORT_DISP_H*/
#endif /*Disable/Enable content*/
|
0 | repos/zig_workbench/BaseLVGL/lib | repos/zig_workbench/BaseLVGL/lib/lvgl/lv_conf_template.h | /**
* @file lv_conf.h
* Configuration file for v9.0.0-dev
*/
/*
* Copy this file as `lv_conf.h`
* 1. simply next to the `lvgl` folder
* 2. or any other places and
* - define `LV_CONF_INCLUDE_SIMPLE`
* - add the path as include path
*/
/* clang-format off */
#if 0 /*Set it to "1" to enable content*/
#ifndef LV_CONF_H
#define LV_CONF_H
#include <stdint.h>
/*====================
COLOR SETTINGS
*====================*/
/*Color depth: 8 (A8), 16 (RGB565), 24 (RGB888), 32 (XRGB8888)*/
#define LV_COLOR_DEPTH 16
/*=========================
STDLIB WRAPPER SETTINGS
*=========================*/
/* Possible values
* - LV_STDLIB_BUILTIN: LVGL's built in implementation
* - LV_STDLIB_CLIB: Standard C functions, like malloc, strlen, etc
* - LV_STDLIB_MICROPYTHON: MicroPython implementation
* - LV_STDLIB_CUSTOM: Implement the functions externally
*/
#define LV_USE_STDLIB_MALLOC LV_STDLIB_BUILTIN
#define LV_USE_STDLIB_STRING LV_STDLIB_BUILTIN
#define LV_USE_STDLIB_SPRINTF LV_STDLIB_BUILTIN
#if LV_USE_STDLIB_MALLOC == LV_STDLIB_BUILTIN
/*Size of the memory available for `lv_malloc()` in bytes (>= 2kB)*/
#define LV_MEM_SIZE (256 * 1024U) /*[bytes]*/
/*Size of the memory expand for `lv_malloc()` in bytes*/
#define LV_MEM_POOL_EXPAND_SIZE 0
/*Set an address for the memory pool instead of allocating it as a normal array. Can be in external SRAM too.*/
#define LV_MEM_ADR 0 /*0: unused*/
/*Instead of an address give a memory allocator that will be called to get a memory pool for LVGL. E.g. my_malloc*/
#if LV_MEM_ADR == 0
#undef LV_MEM_POOL_INCLUDE
#undef LV_MEM_POOL_ALLOC
#endif
#endif /*LV_USE_MALLOC == LV_STDLIB_BUILTIN*/
/*====================
HAL SETTINGS
*====================*/
/*Default display refresh, input device read and animation step period.*/
#define LV_DEF_REFR_PERIOD 33 /*[ms]*/
/*Default Dot Per Inch. Used to initialize default sizes such as widgets sized, style paddings.
*(Not so important, you can adjust it to modify default sizes and spaces)*/
#define LV_DPI_DEF 130 /*[px/inch]*/
/*========================
* RENDERING CONFIGURATION
*========================*/
/*Align the stride of all layers and images to this bytes*/
#define LV_DRAW_BUF_STRIDE_ALIGN 1
/*Align the start address of draw_buf addresses to this bytes*/
#define LV_DRAW_BUF_ALIGN 4
/* Max. memory to be used for layers */
#define LV_LAYER_MAX_MEMORY_USAGE 150 /*[kB]*/
#define LV_USE_DRAW_SW 1
#if LV_USE_DRAW_SW == 1
/* Set the number of draw unit.
* > 1 requires an operating system enabled in `LV_USE_OS`
* > 1 means multiply threads will render the screen in parallel */
#define LV_DRAW_SW_DRAW_UNIT_CNT 1
/* If a widget has `style_opa < 255` (not `bg_opa`, `text_opa` etc) or not NORMAL blend mode
* it is buffered into a "simple" layer before rendering. The widget can be buffered in smaller chunks.
* "Transformed layers" (if `transform_angle/zoom` are set) use larger buffers
* and can't be drawn in chunks. */
/*The target buffer size for simple layer chunks.*/
#define LV_DRAW_SW_LAYER_SIMPLE_BUF_SIZE (24 * 1024) /*[bytes]*/
/* 0: use a simple renderer capable of drawing only simple rectangles with gradient, images, texts, and straight lines only
* 1: use a complex renderer capable of drawing rounded corners, shadow, skew lines, and arcs too */
#define LV_DRAW_SW_COMPLEX 1
#if LV_DRAW_SW_COMPLEX == 1
/*Allow buffering some shadow calculation.
*LV_DRAW_SW_SHADOW_CACHE_SIZE is the max. shadow size to buffer, where shadow size is `shadow_width + radius`
*Caching has LV_DRAW_SW_SHADOW_CACHE_SIZE^2 RAM cost*/
#define LV_DRAW_SW_SHADOW_CACHE_SIZE 0
/* Set number of maximally cached circle data.
* The circumference of 1/4 circle are saved for anti-aliasing
* radius * 4 bytes are used per circle (the most often used radiuses are saved)
* 0: to disable caching */
#define LV_DRAW_SW_CIRCLE_CACHE_SIZE 4
#endif
#define LV_USE_DRAW_SW_ASM LV_DRAW_SW_ASM_NONE
#if LV_USE_DRAW_SW_ASM == LV_DRAW_SW_ASM_CUSTOM
#define LV_DRAW_SW_ASM_CUSTOM_INCLUDE ""
#endif
#endif
/* Use NXP's VG-Lite GPU on iMX RTxxx platforms. */
#define LV_USE_DRAW_VGLITE 0
/* Use NXP's PXP on iMX RTxxx platforms. */
#define LV_USE_DRAW_PXP 0
/*=================
* OPERATING SYSTEM
*=================*/
/*Select an operating system to use. Possible options:
* - LV_OS_NONE
* - LV_OS_PTHREAD
* - LV_OS_FREERTOS
* - LV_OS_CMSIS_RTOS2
* - LV_OS_RTTHREAD
* - LV_OS_CUSTOM */
#define LV_USE_OS LV_OS_NONE
#if LV_USE_OS == LV_OS_CUSTOM
#define LV_OS_CUSTOM_INCLUDE <stdint.h>
#endif
/*=======================
* FEATURE CONFIGURATION
*=======================*/
/*-------------
* Logging
*-----------*/
/*Enable the log module*/
#define LV_USE_LOG 0
#if LV_USE_LOG
/*How important log should be added:
*LV_LOG_LEVEL_TRACE A lot of logs to give detailed information
*LV_LOG_LEVEL_INFO Log important events
*LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't cause a problem
*LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail
*LV_LOG_LEVEL_USER Only logs added by the user
*LV_LOG_LEVEL_NONE Do not log anything*/
#define LV_LOG_LEVEL LV_LOG_LEVEL_WARN
/*1: Print the log with 'printf';
*0: User need to register a callback with `lv_log_register_print_cb()`*/
#define LV_LOG_PRINTF 0
/*1: Enable print timestamp;
*0: Disable print timestamp*/
#define LV_LOG_USE_TIMESTAMP 1
/*1: Print file and line number of the log;
*0: Do not print file and line number of the log*/
#define LV_LOG_USE_FILE_LINE 1
/*Enable/disable LV_LOG_TRACE in modules that produces a huge number of logs*/
#define LV_LOG_TRACE_MEM 1
#define LV_LOG_TRACE_TIMER 1
#define LV_LOG_TRACE_INDEV 1
#define LV_LOG_TRACE_DISP_REFR 1
#define LV_LOG_TRACE_EVENT 1
#define LV_LOG_TRACE_OBJ_CREATE 1
#define LV_LOG_TRACE_LAYOUT 1
#define LV_LOG_TRACE_ANIM 1
#define LV_LOG_TRACE_CACHE 1
#endif /*LV_USE_LOG*/
/*-------------
* Asserts
*-----------*/
/*Enable asserts if an operation is failed or an invalid data is found.
*If LV_USE_LOG is enabled an error message will be printed on failure*/
#define LV_USE_ASSERT_NULL 1 /*Check if the parameter is NULL. (Very fast, recommended)*/
#define LV_USE_ASSERT_MALLOC 1 /*Checks is the memory is successfully allocated or no. (Very fast, recommended)*/
#define LV_USE_ASSERT_STYLE 0 /*Check if the styles are properly initialized. (Very fast, recommended)*/
#define LV_USE_ASSERT_MEM_INTEGRITY 0 /*Check the integrity of `lv_mem` after critical operations. (Slow)*/
#define LV_USE_ASSERT_OBJ 0 /*Check the object's type and existence (e.g. not deleted). (Slow)*/
/*Add a custom handler when assert happens e.g. to restart the MCU*/
#define LV_ASSERT_HANDLER_INCLUDE <stdint.h>
#define LV_ASSERT_HANDLER while(1); /*Halt by default*/
/*-------------
* Debug
*-----------*/
/*1: Draw random colored rectangles over the redrawn areas*/
#define LV_USE_REFR_DEBUG 0
/*1: Draw a red overlay for ARGB layers and a green overlay for RGB layers*/
#define LV_USE_LAYER_DEBUG 0
/*1: Draw overlays with different colors for each draw_unit's tasks.
*Also add the index number of the draw unit on white background.
*For layers add the index number of the draw unit on black background.*/
#define LV_USE_PARALLEL_DRAW_DEBUG 0
/*------------------
* STATUS MONITORING
*------------------*/
/*1: Show CPU usage and FPS count
* Requires `LV_USE_SYSMON = 1`*/
#define LV_USE_PERF_MONITOR 0
#if LV_USE_PERF_MONITOR
#define LV_USE_PERF_MONITOR_POS LV_ALIGN_BOTTOM_RIGHT
/*0: Displays performance data on the screen, 1: Prints performance data using log.*/
#define LV_USE_PERF_MONITOR_LOG_MODE 0
#endif
/*1: Show the used memory and the memory fragmentation
* Requires `LV_USE_BUILTIN_MALLOC = 1`
* Requires `LV_USE_SYSMON = 1`*/
#define LV_USE_MEM_MONITOR 0
#if LV_USE_MEM_MONITOR
#define LV_USE_MEM_MONITOR_POS LV_ALIGN_BOTTOM_LEFT
#endif
/*-------------
* Others
*-----------*/
/*Maximum buffer size to allocate for rotation.
*Only used if software rotation is enabled in the display driver.*/
#define LV_DISPLAY_ROT_MAX_BUF (10*1024)
#define LV_ENABLE_GLOBAL_CUSTOM 0
#if LV_ENABLE_GLOBAL_CUSTOM
/*Header to include for the custom 'lv_global' function"*/
#define LV_GLOBAL_CUSTOM_INCLUDE <stdint.h>
#endif
/*Default cache size in bytes.
*Used by image decoders such as `lv_lodepng` to keep the decoded image in the memory.
*Data larger than the size of the cache also can be allocated but
*will be dropped immediately after usage.*/
#define LV_CACHE_DEF_SIZE 0
/*Number of stops allowed per gradient. Increase this to allow more stops.
*This adds (sizeof(lv_color_t) + 1) bytes per additional stop*/
#define LV_GRADIENT_MAX_STOPS 2
/* Adjust color mix functions rounding. GPUs might calculate color mix (blending) differently.
* 0: round down, 64: round up from x.75, 128: round up from half, 192: round up from x.25, 254: round up */
#define LV_COLOR_MIX_ROUND_OFS 0
/* Add 2 x 32 bit variables to each lv_obj_t to speed up getting style properties */
#define LV_OBJ_STYLE_CACHE 0
/* Add `id` field to `lv_obj_t` */
#define LV_USE_OBJ_ID 0
/* Use lvgl builtin method for obj ID */
#define LV_USE_OBJ_ID_BUILTIN 0
/*Use obj property set/get API*/
#define LV_USE_OBJ_PROPERTY 0
/*=====================
* COMPILER SETTINGS
*====================*/
/*For big endian systems set to 1*/
#define LV_BIG_ENDIAN_SYSTEM 0
/*Define a custom attribute to `lv_tick_inc` function*/
#define LV_ATTRIBUTE_TICK_INC
/*Define a custom attribute to `lv_timer_handler` function*/
#define LV_ATTRIBUTE_TIMER_HANDLER
/*Define a custom attribute to `lv_display_flush_ready` function*/
#define LV_ATTRIBUTE_FLUSH_READY
/*Required alignment size for buffers*/
#define LV_ATTRIBUTE_MEM_ALIGN_SIZE 1
/*Will be added where memories needs to be aligned (with -Os data might not be aligned to boundary by default).
* E.g. __attribute__((aligned(4)))*/
#define LV_ATTRIBUTE_MEM_ALIGN
/*Attribute to mark large constant arrays for example font's bitmaps*/
#define LV_ATTRIBUTE_LARGE_CONST
/*Compiler prefix for a big array declaration in RAM*/
#define LV_ATTRIBUTE_LARGE_RAM_ARRAY
/*Place performance critical functions into a faster memory (e.g RAM)*/
#define LV_ATTRIBUTE_FAST_MEM
/*Export integer constant to binding. This macro is used with constants in the form of LV_<CONST> that
*should also appear on LVGL binding API such as Micropython.*/
#define LV_EXPORT_CONST_INT(int_value) struct _silence_gcc_warning /*The default value just prevents GCC warning*/
/* Use `float` as `lv_value_precise_t` */
#define LV_USE_FLOAT 0
/*==================
* FONT USAGE
*===================*/
/*Montserrat fonts with ASCII range and some symbols using bpp = 4
*https://fonts.google.com/specimen/Montserrat*/
#define LV_FONT_MONTSERRAT_8 0
#define LV_FONT_MONTSERRAT_10 0
#define LV_FONT_MONTSERRAT_12 0
#define LV_FONT_MONTSERRAT_14 1
#define LV_FONT_MONTSERRAT_16 0
#define LV_FONT_MONTSERRAT_18 0
#define LV_FONT_MONTSERRAT_20 0
#define LV_FONT_MONTSERRAT_22 0
#define LV_FONT_MONTSERRAT_24 0
#define LV_FONT_MONTSERRAT_26 0
#define LV_FONT_MONTSERRAT_28 0
#define LV_FONT_MONTSERRAT_30 0
#define LV_FONT_MONTSERRAT_32 0
#define LV_FONT_MONTSERRAT_34 0
#define LV_FONT_MONTSERRAT_36 0
#define LV_FONT_MONTSERRAT_38 0
#define LV_FONT_MONTSERRAT_40 0
#define LV_FONT_MONTSERRAT_42 0
#define LV_FONT_MONTSERRAT_44 0
#define LV_FONT_MONTSERRAT_46 0
#define LV_FONT_MONTSERRAT_48 0
/*Demonstrate special features*/
#define LV_FONT_MONTSERRAT_28_COMPRESSED 0 /*bpp = 3*/
#define LV_FONT_DEJAVU_16_PERSIAN_HEBREW 0 /*Hebrew, Arabic, Persian letters and all their forms*/
#define LV_FONT_SIMSUN_16_CJK 0 /*1000 most common CJK radicals*/
/*Pixel perfect monospace fonts*/
#define LV_FONT_UNSCII_8 0
#define LV_FONT_UNSCII_16 0
/*Optionally declare custom fonts here.
*You can use these fonts as default font too and they will be available globally.
*E.g. #define LV_FONT_CUSTOM_DECLARE LV_FONT_DECLARE(my_font_1) LV_FONT_DECLARE(my_font_2)*/
#define LV_FONT_CUSTOM_DECLARE
/*Always set a default font*/
#define LV_FONT_DEFAULT &lv_font_montserrat_14
/*Enable handling large font and/or fonts with a lot of characters.
*The limit depends on the font size, font face and bpp.
*Compiler error will be triggered if a font needs it.*/
#define LV_FONT_FMT_TXT_LARGE 0
/*Enables/disables support for compressed fonts.*/
#define LV_USE_FONT_COMPRESSED 0
/*Enable drawing placeholders when glyph dsc is not found*/
#define LV_USE_FONT_PLACEHOLDER 1
/*=================
* TEXT SETTINGS
*=================*/
/**
* Select a character encoding for strings.
* Your IDE or editor should have the same character encoding
* - LV_TXT_ENC_UTF8
* - LV_TXT_ENC_ASCII
*/
#define LV_TXT_ENC LV_TXT_ENC_UTF8
/*Can break (wrap) texts on these chars*/
#define LV_TXT_BREAK_CHARS " ,.;:-_)]}"
/*If a word is at least this long, will break wherever "prettiest"
*To disable, set to a value <= 0*/
#define LV_TXT_LINE_BREAK_LONG_LEN 0
/*Minimum number of characters in a long word to put on a line before a break.
*Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/
#define LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN 3
/*Minimum number of characters in a long word to put on a line after a break.
*Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/
#define LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN 3
/*Support bidirectional texts. Allows mixing Left-to-Right and Right-to-Left texts.
*The direction will be processed according to the Unicode Bidirectional Algorithm:
*https://www.w3.org/International/articles/inline-bidi-markup/uba-basics*/
#define LV_USE_BIDI 0
#if LV_USE_BIDI
/*Set the default direction. Supported values:
*`LV_BASE_DIR_LTR` Left-to-Right
*`LV_BASE_DIR_RTL` Right-to-Left
*`LV_BASE_DIR_AUTO` detect texts base direction*/
#define LV_BIDI_BASE_DIR_DEF LV_BASE_DIR_AUTO
#endif
/*Enable Arabic/Persian processing
*In these languages characters should be replaced with an other form based on their position in the text*/
#define LV_USE_ARABIC_PERSIAN_CHARS 0
/*==================
* WIDGETS
*================*/
/*Documentation of the widgets: https://docs.lvgl.io/latest/en/html/widgets/index.html*/
#define LV_WIDGETS_HAS_DEFAULT_VALUE 1
#define LV_USE_ANIMIMG 1
#define LV_USE_ARC 1
#define LV_USE_BAR 1
#define LV_USE_BTN 1
#define LV_USE_BTNMATRIX 1
#define LV_USE_CALENDAR 1
#if LV_USE_CALENDAR
#define LV_CALENDAR_WEEK_STARTS_MONDAY 0
#if LV_CALENDAR_WEEK_STARTS_MONDAY
#define LV_CALENDAR_DEFAULT_DAY_NAMES {"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"}
#else
#define LV_CALENDAR_DEFAULT_DAY_NAMES {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"}
#endif
#define LV_CALENDAR_DEFAULT_MONTH_NAMES {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
#define LV_USE_CALENDAR_HEADER_ARROW 1
#define LV_USE_CALENDAR_HEADER_DROPDOWN 1
#endif /*LV_USE_CALENDAR*/
#define LV_USE_CANVAS 1
#define LV_USE_CHART 1
#define LV_USE_CHECKBOX 1
#define LV_USE_DROPDOWN 1 /*Requires: lv_label*/
#define LV_USE_IMG 1 /*Requires: lv_label*/
#define LV_USE_IMGBTN 1
#define LV_USE_KEYBOARD 1
#define LV_USE_LABEL 1
#if LV_USE_LABEL
#define LV_LABEL_TEXT_SELECTION 1 /*Enable selecting text of the label*/
#define LV_LABEL_LONG_TXT_HINT 1 /*Store some extra info in labels to speed up drawing of very long texts*/
#endif
#define LV_USE_LED 1
#define LV_USE_LINE 1
#define LV_USE_LIST 1
#define LV_USE_MENU 1
#define LV_USE_METER 1
#define LV_USE_MSGBOX 1
#define LV_USE_ROLLER 1 /*Requires: lv_label*/
#define LV_USE_SCALE 1
#define LV_USE_SLIDER 1 /*Requires: lv_bar*/
#define LV_USE_SPAN 1
#if LV_USE_SPAN
/*A line text can contain maximum num of span descriptor */
#define LV_SPAN_SNIPPET_STACK_SIZE 64
#endif
#define LV_USE_SPINBOX 1
#define LV_USE_SPINNER 1
#define LV_USE_SWITCH 1
#define LV_USE_TEXTAREA 1 /*Requires: lv_label*/
#if LV_USE_TEXTAREA != 0
#define LV_TEXTAREA_DEF_PWD_SHOW_TIME 1500 /*ms*/
#endif
#define LV_USE_TABLE 1
#define LV_USE_TABVIEW 1
#define LV_USE_TILEVIEW 1
#define LV_USE_WIN 1
/*==================
* THEMES
*==================*/
/*A simple, impressive and very complete theme*/
#define LV_USE_THEME_DEFAULT 1
#if LV_USE_THEME_DEFAULT
/*0: Light mode; 1: Dark mode*/
#define LV_THEME_DEFAULT_DARK 0
/*1: Enable grow on press*/
#define LV_THEME_DEFAULT_GROW 1
/*Default transition time in [ms]*/
#define LV_THEME_DEFAULT_TRANSITION_TIME 80
#endif /*LV_USE_THEME_DEFAULT*/
/*A very simple theme that is a good starting point for a custom theme*/
#define LV_USE_THEME_BASIC 1
/*A theme designed for monochrome displays*/
#define LV_USE_THEME_MONO 1
/*==================
* LAYOUTS
*==================*/
/*A layout similar to Flexbox in CSS.*/
#define LV_USE_FLEX 1
/*A layout similar to Grid in CSS.*/
#define LV_USE_GRID 1
/*====================
* 3RD PARTS LIBRARIES
*====================*/
/*File system interfaces for common APIs */
/*API for fopen, fread, etc*/
#define LV_USE_FS_STDIO 0
#if LV_USE_FS_STDIO
#define LV_FS_STDIO_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#define LV_FS_STDIO_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
#define LV_FS_STDIO_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
/*API for open, read, etc*/
#define LV_USE_FS_POSIX 0
#if LV_USE_FS_POSIX
#define LV_FS_POSIX_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#define LV_FS_POSIX_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
#define LV_FS_POSIX_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
/*API for CreateFile, ReadFile, etc*/
#define LV_USE_FS_WIN32 0
#if LV_USE_FS_WIN32
#define LV_FS_WIN32_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#define LV_FS_WIN32_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
#define LV_FS_WIN32_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
/*API for FATFS (needs to be added separately). Uses f_open, f_read, etc*/
#define LV_USE_FS_FATFS 0
#if LV_USE_FS_FATFS
#define LV_FS_FATFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#define LV_FS_FATFS_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
/*API for memory-mapped file access. */
#define LV_USE_FS_MEMFS 0
#if LV_USE_FS_MEMFS
#define LV_FS_MEMFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#endif
/*LODEPNG decoder library*/
#define LV_USE_LODEPNG 0
/*PNG decoder(libpng) library*/
#define LV_USE_LIBPNG 0
/*BMP decoder library*/
#define LV_USE_BMP 0
/* JPG + split JPG decoder library.
* Split JPG is a custom format optimized for embedded systems. */
#define LV_USE_TJPGD 0
/* libjpeg-turbo decoder library.
* Supports complete JPEG specifications and high-performance JPEG decoding. */
#define LV_USE_LIBJPEG_TURBO 0
/*GIF decoder library*/
#define LV_USE_GIF 0
/*Decode bin images to RAM*/
#define LV_BIN_DECODER_RAM_LOAD 0
/*QR code library*/
#define LV_USE_QRCODE 0
/*Barcode code library*/
#define LV_USE_BARCODE 0
/*FreeType library*/
#define LV_USE_FREETYPE 0
#if LV_USE_FREETYPE
/*Memory used by FreeType to cache characters [bytes]*/
#define LV_FREETYPE_CACHE_SIZE (64 * 1024)
/*Let FreeType to use LVGL memory and file porting*/
#define LV_FREETYPE_USE_LVGL_PORT 0
/* 1: bitmap cache use the sbit cache, 0:bitmap cache use the image cache. */
/* sbit cache:it is much more memory efficient for small bitmaps(font size < 256) */
/* if font size >= 256, must be configured as image cache */
#define LV_FREETYPE_SBIT_CACHE 0
/* Maximum number of opened FT_Face/FT_Size objects managed by this cache instance. */
/* (0:use system defaults) */
#define LV_FREETYPE_CACHE_FT_FACES 4
#define LV_FREETYPE_CACHE_FT_SIZES 4
#endif
/* Built-in TTF decoder */
#define LV_USE_TINY_TTF 0
#if LV_USE_TINY_TTF
/* Enable loading TTF data from files */
#define LV_TINY_TTF_FILE_SUPPORT 0
#endif
/*Rlottie library*/
#define LV_USE_RLOTTIE 0
/*FFmpeg library for image decoding and playing videos
*Supports all major image formats so do not enable other image decoder with it*/
#define LV_USE_FFMPEG 0
#if LV_USE_FFMPEG
/*Dump input information to stderr*/
#define LV_FFMPEG_DUMP_FORMAT 0
#endif
/*==================
* OTHERS
*==================*/
/*1: Enable API to take snapshot for object*/
#define LV_USE_SNAPSHOT 0
/*1: Enable system monitor component*/
#define LV_USE_SYSMON 0
/*1: Enable the runtime performance profiler*/
#define LV_USE_PROFILER 0
#if LV_USE_PROFILER
/*1: Enable the built-in profiler*/
#define LV_USE_PROFILER_BUILTIN 1
#if LV_USE_PROFILER_BUILTIN
/*Default profiler trace buffer size*/
#define LV_PROFILER_BUILTIN_BUF_SIZE (16 * 1024) /*[bytes]*/
#endif
/*Header to include for the profiler*/
#define LV_PROFILER_INCLUDE "lvgl/src/misc/lv_profiler_builtin.h"
/*Profiler start point function*/
#define LV_PROFILER_BEGIN LV_PROFILER_BUILTIN_BEGIN
/*Profiler end point function*/
#define LV_PROFILER_END LV_PROFILER_BUILTIN_END
/*Profiler start point function with custom tag*/
#define LV_PROFILER_BEGIN_TAG LV_PROFILER_BUILTIN_BEGIN_TAG
/*Profiler end point function with custom tag*/
#define LV_PROFILER_END_TAG LV_PROFILER_BUILTIN_END_TAG
#endif
/*1: Enable Monkey test*/
#define LV_USE_MONKEY 0
/*1: Enable grid navigation*/
#define LV_USE_GRIDNAV 0
/*1: Enable lv_obj fragment*/
#define LV_USE_FRAGMENT 0
/*1: Support using images as font in label or span widgets */
#define LV_USE_IMGFONT 0
#if LV_USE_IMGFONT
/*Imgfont image file path maximum length*/
#define LV_IMGFONT_PATH_MAX_LEN 64
/*1: Use img cache to buffer header information*/
#define LV_IMGFONT_USE_IMAGE_CACHE_HEADER 0
#endif
/*1: Enable an observer pattern implementation*/
#define LV_USE_OBSERVER 0
/*1: Enable Pinyin input method*/
/*Requires: lv_keyboard*/
#define LV_USE_IME_PINYIN 0
#if LV_USE_IME_PINYIN
/*1: Use default thesaurus*/
/*If you do not use the default thesaurus, be sure to use `lv_ime_pinyin` after setting the thesauruss*/
#define LV_IME_PINYIN_USE_DEFAULT_DICT 1
/*Set the maximum number of candidate panels that can be displayed*/
/*This needs to be adjusted according to the size of the screen*/
#define LV_IME_PINYIN_CAND_TEXT_NUM 6
/*Use 9 key input(k9)*/
#define LV_IME_PINYIN_USE_K9_MODE 1
#if LV_IME_PINYIN_USE_K9_MODE == 1
#define LV_IME_PINYIN_K9_CAND_TEXT_NUM 3
#endif // LV_IME_PINYIN_USE_K9_MODE
#endif
/*1: Enable file explorer*/
/*Requires: lv_table*/
#define LV_USE_FILE_EXPLORER 0
#if LV_USE_FILE_EXPLORER
/*Maximum length of path*/
#define LV_FILE_EXPLORER_PATH_MAX_LEN (128)
/*Quick access bar, 1:use, 0:not use*/
/*Requires: lv_list*/
#define LV_FILE_EXPLORER_QUICK_ACCESS 1
#endif
/*==================
* DEVICES
*==================*/
/*Use SDL to open window on PC and handle mouse and keyboard*/
#define LV_USE_SDL 0
#if LV_USE_SDL
#define LV_SDL_INCLUDE_PATH <SDL2/SDL.h>
#define LV_SDL_RENDER_MODE LV_DISPLAY_RENDER_MODE_DIRECT /*LV_DISPLAY_RENDER_MODE_DIRECT is recommended for best performance*/
#define LV_SDL_BUF_COUNT 1 /*1 or 2*/
#define LV_SDL_FULLSCREEN 0 /*1: Make the window full screen by default*/
#define LV_SDL_DIRECT_EXIT 1 /*1: Exit the application when all SDL windows are closed*/
#endif
/*Driver for /dev/fb*/
#define LV_USE_LINUX_FBDEV 0
#if LV_USE_LINUX_FBDEV
#define LV_LINUX_FBDEV_BSD 0
#define LV_LINUX_FBDEV_RENDER_MODE LV_DISPLAY_RENDER_MODE_PARTIAL
#define LV_LINUX_FBDEV_BUFFER_COUNT 0
#define LV_LINUX_FBDEV_BUFFER_SIZE 60
#endif
/*Use Nuttx to open window and handle touchscreen*/
#define LV_USE_NUTTX 0
#if LV_USE_NUTTX
#define LV_USE_NUTTX_LIBUV 0
/*Use Nuttx custom init API to open window and handle touchscreen*/
#define LV_USE_NUTTX_CUSTOM_INIT 0
/*Driver for /dev/lcd*/
#define LV_USE_NUTTX_LCD 0
#if LV_USE_NUTTX_LCD
#define LV_NUTTX_LCD_BUFFER_COUNT 0
#define LV_NUTTX_LCD_BUFFER_SIZE 60
#endif
/*Driver for /dev/input*/
#define LV_USE_NUTTX_TOUCHSCREEN 0
#endif
/*Driver for /dev/dri/card*/
#define LV_USE_LINUX_DRM 0
/*Interface for TFT_eSPI*/
#define LV_USE_TFT_ESPI 0
/*Driver for evdev input devices*/
#define LV_USE_EVDEV 0
/*==================
* EXAMPLES
*==================*/
/*Enable the examples to be built with the library*/
#define LV_BUILD_EXAMPLES 1
/*===================
* DEMO USAGE
====================*/
/*Show some widget. It might be required to increase `LV_MEM_SIZE` */
#define LV_USE_DEMO_WIDGETS 0
#if LV_USE_DEMO_WIDGETS
#define LV_DEMO_WIDGETS_SLIDESHOW 0
#endif
/*Demonstrate the usage of encoder and keyboard*/
#define LV_USE_DEMO_KEYPAD_AND_ENCODER 0
/*Benchmark your system*/
#define LV_USE_DEMO_BENCHMARK 0
/*Render test for each primitives. Requires at least 480x272 display*/
#define LV_USE_DEMO_RENDER 0
/*Stress test for LVGL*/
#define LV_USE_DEMO_STRESS 0
/*Music player demo*/
#define LV_USE_DEMO_MUSIC 0
#if LV_USE_DEMO_MUSIC
#define LV_DEMO_MUSIC_SQUARE 0
#define LV_DEMO_MUSIC_LANDSCAPE 0
#define LV_DEMO_MUSIC_ROUND 0
#define LV_DEMO_MUSIC_LARGE 0
#define LV_DEMO_MUSIC_AUTO_PLAY 0
#endif
/*Flex layout demo*/
#define LV_USE_DEMO_FLEX_LAYOUT 0
/*Smart-phone like multi-language demo*/
#define LV_USE_DEMO_MULTILANG 0
/*Widget transformation demo*/
#define LV_USE_DEMO_TRANSFORM 0
/*Demonstrate scroll settings*/
#define LV_USE_DEMO_SCROLL 0
/*--END OF LV_CONF_H--*/
#endif /*LV_CONF_H*/
#endif /*End of "Content enable"*/
|
0 | repos/zig_workbench/BaseLVGL/lib | repos/zig_workbench/BaseLVGL/lib/lvgl/lv_conf.h | /**
* @file lv_conf.h
* Configuration file for v9.0.0-dev
*/
/*
* Copy this file as `lv_conf.h`
* 1. simply next to the `lvgl` folder
* 2. or any other places and
* - define `LV_CONF_INCLUDE_SIMPLE`
* - add the path as include path
*/
/* clang-format off */
#if 1 /*Set it to "1" to enable content*/
#ifndef LV_CONF_H
#define LV_CONF_H
#include <stdint.h>
/*====================
COLOR SETTINGS
*====================*/
/*Color depth: 8 (A8), 16 (RGB565), 24 (RGB888), 32 (XRGB8888)*/
#define LV_COLOR_DEPTH 32
/*=========================
STDLIB WRAPPER SETTINGS
*=========================*/
/* Possible values
* - LV_STDLIB_BUILTIN: LVGL's built in implementation
* - LV_STDLIB_CLIB: Standard C functions, like malloc, strlen, etc
* - LV_STDLIB_MICROPYTHON: MicroPython implementation
* - LV_STDLIB_CUSTOM: Implement the functions externally
*/
#define LV_USE_STDLIB_MALLOC LV_STDLIB_BUILTIN
#define LV_USE_STDLIB_STRING LV_STDLIB_BUILTIN
#define LV_USE_STDLIB_SPRINTF LV_STDLIB_BUILTIN
#if LV_USE_STDLIB_MALLOC == LV_STDLIB_BUILTIN
/*Size of the memory available for `lv_malloc()` in bytes (>= 2kB)*/
#define LV_MEM_SIZE (1024 * 1024U) /*[bytes]*/
/*Size of the memory expand for `lv_malloc()` in bytes*/
#define LV_MEM_POOL_EXPAND_SIZE 0
/*Set an address for the memory pool instead of allocating it as a normal array. Can be in external SRAM too.*/
#define LV_MEM_ADR 0 /*0: unused*/
/*Instead of an address give a memory allocator that will be called to get a memory pool for LVGL. E.g. my_malloc*/
#if LV_MEM_ADR == 0
#undef LV_MEM_POOL_INCLUDE
#undef LV_MEM_POOL_ALLOC
#endif
#endif /*LV_USE_MALLOC == LV_STDLIB_BUILTIN*/
/*====================
HAL SETTINGS
*====================*/
/*Default display refresh, input device read and animation step period.*/
#define LV_DEF_REFR_PERIOD 10 /*[ms]*/
/*Default Dot Per Inch. Used to initialize default sizes such as widgets sized, style paddings.
*(Not so important, you can adjust it to modify default sizes and spaces)*/
#define LV_DPI_DEF 130 /*[px/inch]*/
/*========================
* RENDERING CONFIGURATION
*========================*/
/*Align the stride of all layers and images to this bytes*/
#define LV_DRAW_BUF_STRIDE_ALIGN 1
/*Align the start address of draw_buf addresses to this bytes*/
#define LV_DRAW_BUF_ALIGN 4
/* Max. memory to be used for layers */
#define LV_LAYER_MAX_MEMORY_USAGE 150 /*[kB]*/
#define LV_USE_DRAW_SW 1
#if LV_USE_DRAW_SW == 1
/* Set the number of draw unit.
* > 1 requires an operating system enabled in `LV_USE_OS`
* > 1 means multiply threads will render the screen in parallel */
#define LV_DRAW_SW_DRAW_UNIT_CNT 1
/* If a widget has `style_opa < 255` (not `bg_opa`, `text_opa` etc) or not NORMAL blend mode
* it is buffered into a "simple" layer before rendering. The widget can be buffered in smaller chunks.
* "Transformed layers" (if `transform_angle/zoom` are set) use larger buffers
* and can't be drawn in chunks. */
/*The target buffer size for simple layer chunks.*/
#define LV_DRAW_SW_LAYER_SIMPLE_BUF_SIZE (24 * 1024) /*[bytes]*/
/* 0: use a simple renderer capable of drawing only simple rectangles with gradient, images, texts, and straight lines only
* 1: use a complex renderer capable of drawing rounded corners, shadow, skew lines, and arcs too */
#define LV_DRAW_SW_COMPLEX 1
#if LV_DRAW_SW_COMPLEX == 1
/*Allow buffering some shadow calculation.
*LV_DRAW_SW_SHADOW_CACHE_SIZE is the max. shadow size to buffer, where shadow size is `shadow_width + radius`
*Caching has LV_DRAW_SW_SHADOW_CACHE_SIZE^2 RAM cost*/
#define LV_DRAW_SW_SHADOW_CACHE_SIZE 0
/* Set number of maximally cached circle data.
* The circumference of 1/4 circle are saved for anti-aliasing
* radius * 4 bytes are used per circle (the most often used radiuses are saved)
* 0: to disable caching */
#define LV_DRAW_SW_CIRCLE_CACHE_SIZE 4
#endif
#define LV_USE_DRAW_SW_ASM LV_DRAW_SW_ASM_NONE
#if LV_USE_DRAW_SW_ASM == LV_DRAW_SW_ASM_CUSTOM
#define LV_DRAW_SW_ASM_CUSTOM_INCLUDE ""
#endif
#endif
/* Use NXP's VG-Lite GPU on iMX RTxxx platforms. */
#define LV_USE_DRAW_VGLITE 0
/* Use NXP's PXP on iMX RTxxx platforms. */
#define LV_USE_DRAW_PXP 0
/*=================
* OPERATING SYSTEM
*=================*/
/*Select an operating system to use. Possible options:
* - LV_OS_NONE
* - LV_OS_PTHREAD
* - LV_OS_FREERTOS
* - LV_OS_CMSIS_RTOS2
* - LV_OS_RTTHREAD
* - LV_OS_CUSTOM */
#define LV_USE_OS LV_OS_NONE
#if LV_USE_OS == LV_OS_CUSTOM
#define LV_OS_CUSTOM_INCLUDE <stdint.h>
#endif
/*=======================
* FEATURE CONFIGURATION
*=======================*/
/*-------------
* Logging
*-----------*/
/*Enable the log module*/
#define LV_USE_LOG 1
#if LV_USE_LOG
/*How important log should be added:
*LV_LOG_LEVEL_TRACE A lot of logs to give detailed information
*LV_LOG_LEVEL_INFO Log important events
*LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't cause a problem
*LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail
*LV_LOG_LEVEL_USER Only logs added by the user
*LV_LOG_LEVEL_NONE Do not log anything*/
#define LV_LOG_LEVEL LV_LOG_LEVEL_WARN
/*1: Print the log with 'printf';
*0: User need to register a callback with `lv_log_register_print_cb()`*/
#define LV_LOG_PRINTF 1
/*1: Enable print timestamp;
*0: Disable print timestamp*/
#define LV_LOG_USE_TIMESTAMP 1
/*1: Print file and line number of the log;
*0: Do not print file and line number of the log*/
#define LV_LOG_USE_FILE_LINE 1
/*Enable/disable LV_LOG_TRACE in modules that produces a huge number of logs*/
#define LV_LOG_TRACE_MEM 1
#define LV_LOG_TRACE_TIMER 1
#define LV_LOG_TRACE_INDEV 1
#define LV_LOG_TRACE_DISP_REFR 1
#define LV_LOG_TRACE_EVENT 1
#define LV_LOG_TRACE_OBJ_CREATE 1
#define LV_LOG_TRACE_LAYOUT 1
#define LV_LOG_TRACE_ANIM 1
#define LV_LOG_TRACE_CACHE 1
#endif /*LV_USE_LOG*/
/*-------------
* Asserts
*-----------*/
/*Enable asserts if an operation is failed or an invalid data is found.
*If LV_USE_LOG is enabled an error message will be printed on failure*/
#define LV_USE_ASSERT_NULL 1 /*Check if the parameter is NULL. (Very fast, recommended)*/
#define LV_USE_ASSERT_MALLOC 1 /*Checks is the memory is successfully allocated or no. (Very fast, recommended)*/
#define LV_USE_ASSERT_STYLE 1 /*Check if the styles are properly initialized. (Very fast, recommended)*/
#define LV_USE_ASSERT_MEM_INTEGRITY 1 /*Check the integrity of `lv_mem` after critical operations. (Slow)*/
#define LV_USE_ASSERT_OBJ 1 /*Check the object's type and existence (e.g. not deleted). (Slow)*/
/*Add a custom handler when assert happens e.g. to restart the MCU*/
#define LV_ASSERT_HANDLER_INCLUDE <stdint.h>
#define LV_ASSERT_HANDLER while(1); /*Halt by default*/
/*-------------
* Debug
*-----------*/
/*1: Draw random colored rectangles over the redrawn areas*/
#define LV_USE_REFR_DEBUG 0
/*1: Draw a red overlay for ARGB layers and a green overlay for RGB layers*/
#define LV_USE_LAYER_DEBUG 0
/*1: Draw overlays with different colors for each draw_unit's tasks.
*Also add the index number of the draw unit on white background.
*For layers add the index number of the draw unit on black background.*/
#define LV_USE_PARALLEL_DRAW_DEBUG 0
/*------------------
* STATUS MONITORING
*------------------*/
/*1: Show CPU usage and FPS count
* Requires `LV_USE_SYSMON = 1`*/
#define LV_USE_PERF_MONITOR 1
#if LV_USE_PERF_MONITOR
#define LV_USE_PERF_MONITOR_POS LV_ALIGN_BOTTOM_RIGHT
/*0: Displays performance data on the screen, 1: Prints performance data using log.*/
#define LV_USE_PERF_MONITOR_LOG_MODE 0
#endif
/*1: Show the used memory and the memory fragmentation
* Requires `LV_USE_BUILTIN_MALLOC = 1`
* Requires `LV_USE_SYSMON = 1`*/
#define LV_USE_MEM_MONITOR 1
#if LV_USE_MEM_MONITOR
#define LV_USE_MEM_MONITOR_POS LV_ALIGN_BOTTOM_LEFT
#endif
/*-------------
* Others
*-----------*/
/*Maximum buffer size to allocate for rotation.
*Only used if software rotation is enabled in the display driver.*/
#define LV_DISPLAY_ROT_MAX_BUF (10*1024)
#define LV_ENABLE_GLOBAL_CUSTOM 0
#if LV_ENABLE_GLOBAL_CUSTOM
/*Header to include for the custom 'lv_global' function"*/
#define LV_GLOBAL_CUSTOM_INCLUDE <stdint.h>
#endif
/*Default cache size in bytes.
*Used by image decoders such as `lv_lodepng` to keep the decoded image in the memory.
*Data larger than the size of the cache also can be allocated but
*will be dropped immediately after usage.*/
#define LV_CACHE_DEF_SIZE 0
/*Number of stops allowed per gradient. Increase this to allow more stops.
*This adds (sizeof(lv_color_t) + 1) bytes per additional stop*/
#define LV_GRADIENT_MAX_STOPS 2
/* Adjust color mix functions rounding. GPUs might calculate color mix (blending) differently.
* 0: round down, 64: round up from x.75, 128: round up from half, 192: round up from x.25, 254: round up */
#define LV_COLOR_MIX_ROUND_OFS 0
/* Add 2 x 32 bit variables to each lv_obj_t to speed up getting style properties */
#define LV_OBJ_STYLE_CACHE 1
/* Add `id` field to `lv_obj_t` */
#define LV_USE_OBJ_ID 0
/* Use lvgl builtin method for obj ID */
#define LV_USE_OBJ_ID_BUILTIN 0
/*Use obj property set/get API*/
#define LV_USE_OBJ_PROPERTY 0
/*=====================
* COMPILER SETTINGS
*====================*/
/*For big endian systems set to 1*/
#define LV_BIG_ENDIAN_SYSTEM 0
/*Define a custom attribute to `lv_tick_inc` function*/
#define LV_ATTRIBUTE_TICK_INC
/*Define a custom attribute to `lv_timer_handler` function*/
#define LV_ATTRIBUTE_TIMER_HANDLER
/*Define a custom attribute to `lv_display_flush_ready` function*/
#define LV_ATTRIBUTE_FLUSH_READY
/*Required alignment size for buffers*/
#define LV_ATTRIBUTE_MEM_ALIGN_SIZE 1
/*Will be added where memories needs to be aligned (with -Os data might not be aligned to boundary by default).
* E.g. __attribute__((aligned(4)))*/
#define LV_ATTRIBUTE_MEM_ALIGN
/*Attribute to mark large constant arrays for example font's bitmaps*/
#define LV_ATTRIBUTE_LARGE_CONST
/*Compiler prefix for a big array declaration in RAM*/
#define LV_ATTRIBUTE_LARGE_RAM_ARRAY
/*Place performance critical functions into a faster memory (e.g RAM)*/
#define LV_ATTRIBUTE_FAST_MEM
/*Export integer constant to binding. This macro is used with constants in the form of LV_<CONST> that
*should also appear on LVGL binding API such as Micropython.*/
#define LV_EXPORT_CONST_INT(int_value) struct _silence_gcc_warning /*The default value just prevents GCC warning*/
/* Use `float` as `lv_value_precise_t` */
#define LV_USE_FLOAT 0
/*==================
* FONT USAGE
*===================*/
/*Montserrat fonts with ASCII range and some symbols using bpp = 4
*https://fonts.google.com/specimen/Montserrat*/
#define LV_FONT_MONTSERRAT_8 1
#define LV_FONT_MONTSERRAT_10 1
#define LV_FONT_MONTSERRAT_12 1
#define LV_FONT_MONTSERRAT_14 1
#define LV_FONT_MONTSERRAT_16 1
#define LV_FONT_MONTSERRAT_18 1
#define LV_FONT_MONTSERRAT_20 1
#define LV_FONT_MONTSERRAT_22 1
#define LV_FONT_MONTSERRAT_24 1
#define LV_FONT_MONTSERRAT_26 1
#define LV_FONT_MONTSERRAT_28 1
#define LV_FONT_MONTSERRAT_30 1
#define LV_FONT_MONTSERRAT_32 1
#define LV_FONT_MONTSERRAT_34 1
#define LV_FONT_MONTSERRAT_36 1
#define LV_FONT_MONTSERRAT_38 1
#define LV_FONT_MONTSERRAT_40 1
#define LV_FONT_MONTSERRAT_42 1
#define LV_FONT_MONTSERRAT_44 1
#define LV_FONT_MONTSERRAT_46 1
#define LV_FONT_MONTSERRAT_48 1
/*Demonstrate special features*/
#define LV_FONT_MONTSERRAT_28_COMPRESSED 1 /*bpp = 3*/
#define LV_FONT_DEJAVU_16_PERSIAN_HEBREW 1 /*Hebrew, Arabic, Persian letters and all their forms*/
#define LV_FONT_SIMSUN_16_CJK 1 /*1000 most common CJK radicals*/
/*Pixel perfect monospace fonts*/
#define LV_FONT_UNSCII_8 1
#define LV_FONT_UNSCII_16 0
/*Optionally declare custom fonts here.
*You can use these fonts as default font too and they will be available globally.
*E.g. #define LV_FONT_CUSTOM_DECLARE LV_FONT_DECLARE(my_font_1) LV_FONT_DECLARE(my_font_2)*/
#define LV_FONT_CUSTOM_DECLARE
/*Always set a default font*/
#define LV_FONT_DEFAULT &lv_font_montserrat_14
/*Enable handling large font and/or fonts with a lot of characters.
*The limit depends on the font size, font face and bpp.
*Compiler error will be triggered if a font needs it.*/
#define LV_FONT_FMT_TXT_LARGE 0
/*Enables/disables support for compressed fonts.*/
#define LV_USE_FONT_COMPRESSED 1
/*Enable drawing placeholders when glyph dsc is not found*/
#define LV_USE_FONT_PLACEHOLDER 1
/*=================
* TEXT SETTINGS
*=================*/
/**
* Select a character encoding for strings.
* Your IDE or editor should have the same character encoding
* - LV_TXT_ENC_UTF8
* - LV_TXT_ENC_ASCII
*/
#define LV_TXT_ENC LV_TXT_ENC_UTF8
/*Can break (wrap) texts on these chars*/
#define LV_TXT_BREAK_CHARS " ,.;:-_)]}"
/*If a word is at least this long, will break wherever "prettiest"
*To disable, set to a value <= 0*/
#define LV_TXT_LINE_BREAK_LONG_LEN 0
/*Minimum number of characters in a long word to put on a line before a break.
*Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/
#define LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN 3
/*Minimum number of characters in a long word to put on a line after a break.
*Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/
#define LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN 3
/*Support bidirectional texts. Allows mixing Left-to-Right and Right-to-Left texts.
*The direction will be processed according to the Unicode Bidirectional Algorithm:
*https://www.w3.org/International/articles/inline-bidi-markup/uba-basics*/
#define LV_USE_BIDI 1
#if LV_USE_BIDI
/*Set the default direction. Supported values:
*`LV_BASE_DIR_LTR` Left-to-Right
*`LV_BASE_DIR_RTL` Right-to-Left
*`LV_BASE_DIR_AUTO` detect texts base direction*/
#define LV_BIDI_BASE_DIR_DEF LV_BASE_DIR_AUTO
#endif
/*Enable Arabic/Persian processing
*In these languages characters should be replaced with an other form based on their position in the text*/
#define LV_USE_ARABIC_PERSIAN_CHARS 1
/*==================
* WIDGETS
*================*/
/*Documentation of the widgets: https://docs.lvgl.io/latest/en/html/widgets/index.html*/
#define LV_WIDGETS_HAS_DEFAULT_VALUE 1
#define LV_USE_ANIMIMG 1
#define LV_USE_ARC 1
#define LV_USE_BAR 1
#define LV_USE_BTN 1
#define LV_USE_BTNMATRIX 1
#define LV_USE_CALENDAR 1
#if LV_USE_CALENDAR
#define LV_CALENDAR_WEEK_STARTS_MONDAY 0
#if LV_CALENDAR_WEEK_STARTS_MONDAY
#define LV_CALENDAR_DEFAULT_DAY_NAMES {"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"}
#else
#define LV_CALENDAR_DEFAULT_DAY_NAMES {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"}
#endif
#define LV_CALENDAR_DEFAULT_MONTH_NAMES {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
#define LV_USE_CALENDAR_HEADER_ARROW 1
#define LV_USE_CALENDAR_HEADER_DROPDOWN 1
#endif /*LV_USE_CALENDAR*/
#define LV_USE_CANVAS 1
#define LV_USE_CHART 1
#define LV_USE_CHECKBOX 1
#define LV_USE_DROPDOWN 1 /*Requires: lv_label*/
#define LV_USE_IMG 1 /*Requires: lv_label*/
#define LV_USE_IMGBTN 1
#define LV_USE_KEYBOARD 1
#define LV_USE_LABEL 1
#if LV_USE_LABEL
#define LV_LABEL_TEXT_SELECTION 1 /*Enable selecting text of the label*/
#define LV_LABEL_LONG_TXT_HINT 1 /*Store some extra info in labels to speed up drawing of very long texts*/
#endif
#define LV_USE_LED 1
#define LV_USE_LINE 1
#define LV_USE_LIST 1
#define LV_USE_MENU 1
#define LV_USE_METER 1
#define LV_USE_MSGBOX 1
#define LV_USE_ROLLER 1 /*Requires: lv_label*/
#define LV_USE_SCALE 1
#define LV_USE_SLIDER 1 /*Requires: lv_bar*/
#define LV_USE_SPAN 1
#if LV_USE_SPAN
/*A line text can contain maximum num of span descriptor */
#define LV_SPAN_SNIPPET_STACK_SIZE 64
#endif
#define LV_USE_SPINBOX 1
#define LV_USE_SPINNER 1
#define LV_USE_SWITCH 1
#define LV_USE_TEXTAREA 1 /*Requires: lv_label*/
#if LV_USE_TEXTAREA != 0
#define LV_TEXTAREA_DEF_PWD_SHOW_TIME 1500 /*ms*/
#endif
#define LV_USE_TABLE 1
#define LV_USE_TABVIEW 1
#define LV_USE_TILEVIEW 1
#define LV_USE_WIN 1
/*==================
* THEMES
*==================*/
/*A simple, impressive and very complete theme*/
#define LV_USE_THEME_DEFAULT 1
#if LV_USE_THEME_DEFAULT
/*0: Light mode; 1: Dark mode*/
#define LV_THEME_DEFAULT_DARK 0
/*1: Enable grow on press*/
#define LV_THEME_DEFAULT_GROW 1
/*Default transition time in [ms]*/
#define LV_THEME_DEFAULT_TRANSITION_TIME 80
#endif /*LV_USE_THEME_DEFAULT*/
/*A very simple theme that is a good starting point for a custom theme*/
#define LV_USE_THEME_BASIC 1
/*A theme designed for monochrome displays*/
#define LV_USE_THEME_MONO 1
/*==================
* LAYOUTS
*==================*/
/*A layout similar to Flexbox in CSS.*/
#define LV_USE_FLEX 1
/*A layout similar to Grid in CSS.*/
#define LV_USE_GRID 1
/*====================
* 3RD PARTS LIBRARIES
*====================*/
/*File system interfaces for common APIs */
/*API for fopen, fread, etc*/
#define LV_USE_FS_STDIO 0
#if LV_USE_FS_STDIO
#define LV_FS_STDIO_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#define LV_FS_STDIO_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
#define LV_FS_STDIO_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
/*API for open, read, etc*/
#define LV_USE_FS_POSIX 0
#if LV_USE_FS_POSIX
#define LV_FS_POSIX_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#define LV_FS_POSIX_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
#define LV_FS_POSIX_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
/*API for CreateFile, ReadFile, etc*/
#define LV_USE_FS_WIN32 1
#if LV_USE_FS_WIN32
#define LV_FS_WIN32_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#define LV_FS_WIN32_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
#define LV_FS_WIN32_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
/*API for FATFS (needs to be added separately). Uses f_open, f_read, etc*/
#define LV_USE_FS_FATFS 0
#if LV_USE_FS_FATFS
#define LV_FS_FATFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#define LV_FS_FATFS_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
/*API for memory-mapped file access. */
#define LV_USE_FS_MEMFS 0
#if LV_USE_FS_MEMFS
#define LV_FS_MEMFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#endif
/*LODEPNG decoder library*/
#define LV_USE_LODEPNG 0
/*PNG decoder(libpng) library*/
#define LV_USE_LIBPNG 0
/*BMP decoder library*/
#define LV_USE_BMP 0
/* JPG + split JPG decoder library.
* Split JPG is a custom format optimized for embedded systems. */
#define LV_USE_TJPGD 0
/* libjpeg-turbo decoder library.
* Supports complete JPEG specifications and high-performance JPEG decoding. */
#define LV_USE_LIBJPEG_TURBO 0
/*GIF decoder library*/
#define LV_USE_GIF 0
/*Decode bin images to RAM*/
#define LV_BIN_DECODER_RAM_LOAD 0
/*QR code library*/
#define LV_USE_QRCODE 0
/*Barcode code library*/
#define LV_USE_BARCODE 0
/*FreeType library*/
#define LV_USE_FREETYPE 0
#if LV_USE_FREETYPE
/*Memory used by FreeType to cache characters [bytes]*/
#define LV_FREETYPE_CACHE_SIZE (64 * 1024)
/*Let FreeType to use LVGL memory and file porting*/
#define LV_FREETYPE_USE_LVGL_PORT 0
/* 1: bitmap cache use the sbit cache, 0:bitmap cache use the image cache. */
/* sbit cache:it is much more memory efficient for small bitmaps(font size < 256) */
/* if font size >= 256, must be configured as image cache */
#define LV_FREETYPE_SBIT_CACHE 0
/* Maximum number of opened FT_Face/FT_Size objects managed by this cache instance. */
/* (0:use system defaults) */
#define LV_FREETYPE_CACHE_FT_FACES 4
#define LV_FREETYPE_CACHE_FT_SIZES 4
#endif
/* Built-in TTF decoder */
#define LV_USE_TINY_TTF 0
#if LV_USE_TINY_TTF
/* Enable loading TTF data from files */
#define LV_TINY_TTF_FILE_SUPPORT 0
#endif
/*Rlottie library*/
#define LV_USE_RLOTTIE 0
/*FFmpeg library for image decoding and playing videos
*Supports all major image formats so do not enable other image decoder with it*/
#define LV_USE_FFMPEG 0
#if LV_USE_FFMPEG
/*Dump input information to stderr*/
#define LV_FFMPEG_DUMP_FORMAT 0
#endif
/*==================
* OTHERS
*==================*/
/*1: Enable API to take snapshot for object*/
#define LV_USE_SNAPSHOT 0
/*1: Enable system monitor component*/
#define LV_USE_SYSMON 1
/*1: Enable the runtime performance profiler*/
#define LV_USE_PROFILER 0
#if LV_USE_PROFILER
/*1: Enable the built-in profiler*/
#define LV_USE_PROFILER_BUILTIN 1
#if LV_USE_PROFILER_BUILTIN
/*Default profiler trace buffer size*/
#define LV_PROFILER_BUILTIN_BUF_SIZE (16 * 1024) /*[bytes]*/
#endif
/*Header to include for the profiler*/
#define LV_PROFILER_INCLUDE "lvgl/src/misc/lv_profiler_builtin.h"
/*Profiler start point function*/
#define LV_PROFILER_BEGIN LV_PROFILER_BUILTIN_BEGIN
/*Profiler end point function*/
#define LV_PROFILER_END LV_PROFILER_BUILTIN_END
/*Profiler start point function with custom tag*/
#define LV_PROFILER_BEGIN_TAG LV_PROFILER_BUILTIN_BEGIN_TAG
/*Profiler end point function with custom tag*/
#define LV_PROFILER_END_TAG LV_PROFILER_BUILTIN_END_TAG
#endif
/*1: Enable Monkey test*/
#define LV_USE_MONKEY 0
/*1: Enable grid navigation*/
#define LV_USE_GRIDNAV 0
/*1: Enable lv_obj fragment*/
#define LV_USE_FRAGMENT 0
/*1: Support using images as font in label or span widgets */
#define LV_USE_IMGFONT 1
#if LV_USE_IMGFONT
/*Imgfont image file path maximum length*/
#define LV_IMGFONT_PATH_MAX_LEN 64
/*1: Use img cache to buffer header information*/
#define LV_IMGFONT_USE_IMAGE_CACHE_HEADER 0
#endif
/*1: Enable an observer pattern implementation*/
#define LV_USE_OBSERVER 1
/*1: Enable Pinyin input method*/
/*Requires: lv_keyboard*/
#define LV_USE_IME_PINYIN 0
#if LV_USE_IME_PINYIN
/*1: Use default thesaurus*/
/*If you do not use the default thesaurus, be sure to use `lv_ime_pinyin` after setting the thesauruss*/
#define LV_IME_PINYIN_USE_DEFAULT_DICT 1
/*Set the maximum number of candidate panels that can be displayed*/
/*This needs to be adjusted according to the size of the screen*/
#define LV_IME_PINYIN_CAND_TEXT_NUM 6
/*Use 9 key input(k9)*/
#define LV_IME_PINYIN_USE_K9_MODE 1
#if LV_IME_PINYIN_USE_K9_MODE == 1
#define LV_IME_PINYIN_K9_CAND_TEXT_NUM 3
#endif // LV_IME_PINYIN_USE_K9_MODE
#endif
/*1: Enable file explorer*/
/*Requires: lv_table*/
#define LV_USE_FILE_EXPLORER 0
#if LV_USE_FILE_EXPLORER
/*Maximum length of path*/
#define LV_FILE_EXPLORER_PATH_MAX_LEN (128)
/*Quick access bar, 1:use, 0:not use*/
/*Requires: lv_list*/
#define LV_FILE_EXPLORER_QUICK_ACCESS 1
#endif
/*==================
* DEVICES
*==================*/
/*Use SDL to open window on PC and handle mouse and keyboard*/
#define LV_USE_SDL 0
#if LV_USE_SDL
#define LV_SDL_INCLUDE_PATH <SDL2/SDL.h>
#define LV_SDL_RENDER_MODE LV_DISPLAY_RENDER_MODE_DIRECT /*LV_DISPLAY_RENDER_MODE_DIRECT is recommended for best performance*/
#define LV_SDL_BUF_COUNT 1 /*1 or 2*/
#define LV_SDL_FULLSCREEN 0 /*1: Make the window full screen by default*/
#define LV_SDL_DIRECT_EXIT 1 /*1: Exit the application when all SDL windows are closed*/
#endif
/*Driver for /dev/fb*/
#define LV_USE_LINUX_FBDEV 0
#if LV_USE_LINUX_FBDEV
#define LV_LINUX_FBDEV_BSD 0
#define LV_LINUX_FBDEV_RENDER_MODE LV_DISPLAY_RENDER_MODE_PARTIAL
#define LV_LINUX_FBDEV_BUFFER_COUNT 0
#define LV_LINUX_FBDEV_BUFFER_SIZE 60
#endif
/*Use Nuttx to open window and handle touchscreen*/
#define LV_USE_NUTTX 0
#if LV_USE_NUTTX
#define LV_USE_NUTTX_LIBUV 0
/*Use Nuttx custom init API to open window and handle touchscreen*/
#define LV_USE_NUTTX_CUSTOM_INIT 0
/*Driver for /dev/lcd*/
#define LV_USE_NUTTX_LCD 0
#if LV_USE_NUTTX_LCD
#define LV_NUTTX_LCD_BUFFER_COUNT 0
#define LV_NUTTX_LCD_BUFFER_SIZE 60
#endif
/*Driver for /dev/input*/
#define LV_USE_NUTTX_TOUCHSCREEN 0
#endif
/*Driver for /dev/dri/card*/
#define LV_USE_LINUX_DRM 0
/*Interface for TFT_eSPI*/
#define LV_USE_TFT_ESPI 0
/*Driver for evdev input devices*/
#define LV_USE_EVDEV 0
/*==================
* EXAMPLES
*==================*/
/*Enable the examples to be built with the library*/
#define LV_BUILD_EXAMPLES 1
/*===================
* DEMO USAGE
====================*/
/*Show some widget. It might be required to increase `LV_MEM_SIZE` */
#define LV_USE_DEMO_WIDGETS 1
#if LV_USE_DEMO_WIDGETS
#define LV_DEMO_WIDGETS_SLIDESHOW 0
#endif
/*Demonstrate the usage of encoder and keyboard*/
#define LV_USE_DEMO_KEYPAD_AND_ENCODER 1
/*Benchmark your system*/
#define LV_USE_DEMO_BENCHMARK 1
/*Render test for each primitives. Requires at least 480x272 display*/
#define LV_USE_DEMO_RENDER 1
/*Stress test for LVGL*/
#define LV_USE_DEMO_STRESS 1
/*Music player demo*/
#define LV_USE_DEMO_MUSIC 0
#if LV_USE_DEMO_MUSIC
#define LV_DEMO_MUSIC_SQUARE 1
#define LV_DEMO_MUSIC_LANDSCAPE 1
#define LV_DEMO_MUSIC_ROUND 1
#define LV_DEMO_MUSIC_LARGE 1
#define LV_DEMO_MUSIC_AUTO_PLAY 1
#endif
/*Flex layout demo*/
#define LV_USE_DEMO_FLEX_LAYOUT 1
/*Smart-phone like multi-language demo*/
#define LV_USE_DEMO_MULTILANG 1
/*Widget transformation demo*/
#define LV_USE_DEMO_TRANSFORM 1
/*Demonstrate scroll settings*/
#define LV_USE_DEMO_SCROLL 1
/*--END OF LV_CONF_H--*/
#endif /*LV_CONF_H*/
#endif /*End of "Content enable"*/
|
0 | repos/zig_workbench/BaseLVGL/lib | repos/zig_workbench/BaseLVGL/lib/lvgl/LICENCE.txt | MIT licence
Copyright (c) 2021 LVGL Kft
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.
|
0 | repos/zig_workbench/BaseLVGL/lib | repos/zig_workbench/BaseLVGL/lib/lvgl/lvgl.h | /**
* @file lvgl.h
* Include all LVGL related headers
*/
#ifndef LVGL_H
#define LVGL_H
#ifdef __cplusplus
extern "C" {
#endif
/***************************
* CURRENT VERSION OF LVGL
***************************/
#define LVGL_VERSION_MAJOR 9
#define LVGL_VERSION_MINOR 0
#define LVGL_VERSION_PATCH 0
#define LVGL_VERSION_INFO "dev"
/*********************
* INCLUDES
*********************/
#include "src/lv_init.h"
#include "src/stdlib/lv_mem.h"
#include "src/stdlib/lv_string.h"
#include "src/stdlib/lv_sprintf.h"
#include "src/misc/lv_log.h"
#include "src/misc/lv_timer.h"
#include "src/misc/lv_math.h"
#include "src/misc/lv_async.h"
#include "src/misc/lv_anim_timeline.h"
#include "src/misc/lv_profiler_builtin.h"
#include "src/tick/lv_tick.h"
#include "src/core/lv_obj.h"
#include "src/core/lv_group.h"
#include "src/indev/lv_indev.h"
#include "src/core/lv_refr.h"
#include "src/display/lv_display.h"
#include "src/font/lv_font.h"
#include "src/font/lv_font_loader.h"
#include "src/font/lv_font_fmt_txt.h"
#include "src/widgets/animimage/lv_animimage.h"
#include "src/widgets/arc/lv_arc.h"
#include "src/widgets/bar/lv_bar.h"
#include "src/widgets/button/lv_button.h"
#include "src/widgets/buttonmatrix/lv_buttonmatrix.h"
#include "src/widgets/calendar/lv_calendar.h"
#include "src/widgets/canvas/lv_canvas.h"
#include "src/widgets/chart/lv_chart.h"
#include "src/widgets/checkbox/lv_checkbox.h"
#include "src/widgets/dropdown/lv_dropdown.h"
#include "src/widgets/image/lv_image.h"
#include "src/widgets/imgbtn/lv_imgbtn.h"
#include "src/widgets/keyboard/lv_keyboard.h"
#include "src/widgets/label/lv_label.h"
#include "src/widgets/led/lv_led.h"
#include "src/widgets/line/lv_line.h"
#include "src/widgets/list/lv_list.h"
#include "src/widgets/menu/lv_menu.h"
#include "src/widgets/msgbox/lv_msgbox.h"
#include "src/widgets/roller/lv_roller.h"
#include "src/widgets/scale/lv_scale.h"
#include "src/widgets/slider/lv_slider.h"
#include "src/widgets/span/lv_span.h"
#include "src/widgets/spinbox/lv_spinbox.h"
#include "src/widgets/spinner/lv_spinner.h"
#include "src/widgets/switch/lv_switch.h"
#include "src/widgets/table/lv_table.h"
#include "src/widgets/tabview/lv_tabview.h"
#include "src/widgets/textarea/lv_textarea.h"
#include "src/widgets/tileview/lv_tileview.h"
#include "src/widgets/win/lv_win.h"
#include "src/others/snapshot/lv_snapshot.h"
#include "src/others/sysmon/lv_sysmon.h"
#include "src/others/monkey/lv_monkey.h"
#include "src/others/gridnav/lv_gridnav.h"
#include "src/others/fragment/lv_fragment.h"
#include "src/others/imgfont/lv_imgfont.h"
#include "src/others/observer/lv_observer.h"
#include "src/others/ime/lv_ime_pinyin.h"
#include "src/others/file_explorer/lv_file_explorer.h"
#include "src/libs/barcode/lv_barcode.h"
#include "src/libs/bmp/lv_bmp.h"
#include "src/libs/fsdrv/lv_fsdrv.h"
#include "src/libs/lodepng/lv_lodepng.h"
#include "src/libs/libpng/lv_libpng.h"
#include "src/libs/gif/lv_gif.h"
#include "src/libs/qrcode/lv_qrcode.h"
#include "src/libs/tjpgd/lv_tjpgd.h"
#include "src/libs/libjpeg_turbo/lv_libjpeg_turbo.h"
#include "src/libs/freetype/lv_freetype.h"
#include "src/libs/rlottie/lv_rlottie.h"
#include "src/libs/ffmpeg/lv_ffmpeg.h"
#include "src/libs/tiny_ttf/lv_tiny_ttf.h"
#include "src/layouts/lv_layout.h"
#include "src/draw/lv_draw.h"
#include "src/themes/lv_theme.h"
#include "src/lv_api_map.h"
#include "src/dev/sdl/lv_sdl_window.h"
#include "src/dev/sdl/lv_sdl_mouse.h"
#include "src/dev/sdl/lv_sdl_mousewheel.h"
#include "src/dev/sdl/lv_sdl_keyboard.h"
#include "src/dev/display/drm/lv_linux_drm.h"
#include "src/dev/display/fb/lv_linux_fbdev.h"
#include "src/dev/nuttx/lv_nuttx_entry.h"
#include "src/dev/nuttx/lv_nuttx_fbdev.h"
#include "src/dev/nuttx/lv_nuttx_touchscreen.h"
#include "src/dev/nuttx/lv_nuttx_lcd.h"
#include "src/dev/nuttx/lv_nuttx_libuv.h"
#include "src/dev/evdev/lv_evdev.h"
#include "src/core/lv_global.h"
/*********************
* DEFINES
*********************/
#ifndef LV_USE_DEV_VERSION
#warning "You are using the development version of LVGL which is not stable at this moment. For production use the release/v8.3 branch. To silence this warning add #define LV_USE_DEV_VERSION to lv_conf.h"
#endif
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**********************
* MACROS
**********************/
/** Gives 1 if the x.y.z version is supported in the current version
* Usage:
*
* - Require v6
* #if LV_VERSION_CHECK(6,0,0)
* new_func_in_v6();
* #endif
*
*
* - Require at least v5.3
* #if LV_VERSION_CHECK(5,3,0)
* new_feature_from_v5_3();
* #endif
*
*
* - Require v5.3.2 bugfixes
* #if LV_VERSION_CHECK(5,3,2)
* bugfix_in_v5_3_2();
* #endif
*
*/
#define LV_VERSION_CHECK(x,y,z) (x == LVGL_VERSION_MAJOR && (y < LVGL_VERSION_MINOR || (y == LVGL_VERSION_MINOR && z <= LVGL_VERSION_PATCH)))
/**
* Wrapper functions for VERSION macros
*/
static inline int lv_version_major(void)
{
return LVGL_VERSION_MAJOR;
}
static inline int lv_version_minor(void)
{
return LVGL_VERSION_MINOR;
}
static inline int lv_version_patch(void)
{
return LVGL_VERSION_PATCH;
}
static inline const char * lv_version_info(void)
{
return LVGL_VERSION_INFO;
}
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LVGL_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib | repos/zig_workbench/BaseLVGL/lib/lvgl/c_bundle.c | #include "src/core/lv_group.c"
#include "src/core/lv_obj_class.c"
#include "src/core/lv_obj_draw.c"
#include "src/core/lv_obj_event.c"
#include "src/core/lv_obj_id_builtin.c"
#include "src/core/lv_obj_pos.c"
#include "src/core/lv_obj_property.c"
#include "src/core/lv_obj_scroll.c"
#include "src/core/lv_obj_style.c"
#include "src/core/lv_obj_style_gen.c"
#include "src/core/lv_obj_tree.c"
#include "src/core/lv_obj.c"
#include "src/core/lv_refr.c"
#include "src/indev/lv_indev.c"
#include "src/indev/lv_indev_scroll.c"
#include "src/stdlib/lv_mem.c"
#include "src/stdlib/builtin/lv_mem_core_builtin.c"
#include "src/stdlib/builtin/lv_string_builtin.c"
#include "src/stdlib/builtin/lv_sprintf_builtin.c"
#include "src/stdlib/builtin/lv_tlsf.c"
#include "src/misc/lv_anim.c"
#include "src/misc/lv_anim_timeline.c"
#include "src/misc/lv_area.c"
#include "src/misc/lv_async.c"
#include "src/misc/lv_bidi.c"
#include "src/misc/lv_cache.c"
#include "src/misc/lv_cache_builtin.c"
#include "src/misc/lv_color.c"
#include "src/misc/lv_color_op.c"
#include "src/misc/lv_event.c"
#include "src/misc/lv_fs.c"
#include "src/misc/lv_ll.c"
#include "src/misc/lv_log.c"
#include "src/misc/lv_lru.c"
#include "src/misc/lv_math.c"
#include "src/misc/lv_palette.c"
#include "src/misc/lv_profiler_builtin.c"
#include "src/misc/lv_style.c"
#include "src/misc/lv_style_gen.c"
#include "src/misc/lv_templ.c"
#include "src/misc/lv_text.c"
#include "src/misc/lv_text_ap.c"
#include "src/misc/lv_timer.c"
#include "src/misc/lv_utils.c"
#include "src/libs/fsdrv/lv_fs_win32.c"
#include "src/others/file_explorer/lv_file_explorer.c"
#include "src/others/fragment/lv_fragment.c"
#include "src/others/fragment/lv_fragment_manager.c"
#include "src/others/gridnav/lv_gridnav.c"
#include "src/others/ime/lv_ime_pinyin.c"
#include "src/others/imgfont/lv_imgfont.c"
#include "src/others/monkey/lv_monkey.c"
#include "src/others/observer/lv_observer.c"
#include "src/others/snapshot/lv_snapshot.c"
#include "src/others/sysmon/lv_sysmon.c"
#include "src/layouts/lv_layout.c"
#include "src/layouts/flex/lv_flex.c"
#include "src/layouts/grid/lv_grid.c"
#include "src/tick/lv_tick.c"
#include "src/draw/lv_draw.c"
#include "src/draw/lv_draw_arc.c"
#include "src/draw/lv_draw_buf.c"
#include "src/draw/lv_draw_image.c"
#include "src/draw/lv_draw_label.c"
#include "src/draw/lv_draw_line.c"
#include "src/draw/lv_draw_mask.c"
#include "src/draw/lv_draw_rect.c"
#include "src/draw/lv_draw_triangle.c"
#include "src/draw/lv_image_buf.c"
#include "src/draw/lv_image_decoder.c"
#include "src/draw/sw/lv_draw_sw.c"
#include "src/draw/sw/lv_draw_sw_arc.c"
#include "src/draw/sw/lv_draw_sw_bg_img.c"
#include "src/draw/sw/lv_draw_sw_border.c"
#include "src/draw/sw/lv_draw_sw_box_shadow.c"
#include "src/draw/sw/lv_draw_sw_fill.c"
#include "src/draw/sw/lv_draw_sw_gradient.c"
#include "src/draw/sw/lv_draw_sw_img.c"
#include "src/draw/sw/lv_draw_sw_letter.c"
#include "src/draw/sw/lv_draw_sw_line.c"
#include "src/draw/sw/lv_draw_sw_mask.c"
#include "src/draw/sw/lv_draw_sw_mask_rect.c"
#include "src/draw/sw/lv_draw_sw_transform.c"
#include "src/draw/sw/lv_draw_sw_triangle.c"
#include "src/draw/sw/blend/lv_draw_sw_blend.c"
#include "src/draw/sw/blend/lv_draw_sw_blend_to_argb8888.c"
#include "src/draw/sw/blend/lv_draw_sw_blend_to_rgb565.c"
#include "src/draw/sw/blend/lv_draw_sw_blend_to_rgb888.c"
#include "src/display/lv_display.c"
#include "src/osal/lv_os_none.c"
#include "src/font/lv_font.c"
#include "src/font/lv_font_fmt_txt.c"
#include "src/font/lv_font_montserrat_14.c"
#include "src/themes/lv_theme.c"
#include "src/themes/basic/lv_theme_basic.c"
#include "src/themes/default/lv_theme_default.c"
#include "src/themes/mono/lv_theme_mono.c"
#include "src/widgets/arc/lv_arc.c"
#include "src/widgets/bar/lv_bar.c"
#include "src/widgets/button/lv_button.c"
#include "src/widgets/buttonmatrix/lv_buttonmatrix.c"
#include "src/widgets/calendar/lv_calendar.c"
#include "src/widgets/calendar/lv_calendar_header_arrow.c"
#include "src/widgets/calendar/lv_calendar_header_dropdown.c"
#include "src/widgets/canvas/lv_canvas.c"
#include "src/widgets/chart/lv_chart.c"
#include "src/widgets/checkbox/lv_checkbox.c"
#include "src/widgets/dropdown/lv_dropdown.c"
#include "src/widgets/image/lv_image.c"
#include "src/widgets/imgbtn/lv_imgbtn.c"
#include "src/widgets/keyboard/lv_keyboard.c"
#include "src/widgets/label/lv_label.c"
#include "src/widgets/led/lv_led.c"
#include "src/widgets/line/lv_line.c"
#include "src/widgets/list/lv_list.c"
#include "src/widgets/menu/lv_menu.c"
#include "src/widgets/msgbox/lv_msgbox.c"
#include "src/widgets/objx_templ/lv_objx_templ.c"
#include "src/widgets/roller/lv_roller.c"
#include "src/widgets/scale/lv_scale.c"
#include "src/widgets/slider/lv_slider.c"
#include "src/widgets/span/lv_span.c"
#include "src/widgets/spinbox/lv_spinbox.c"
#include "src/widgets/spinner/lv_spinner.c"
#include "src/widgets/switch/lv_switch.c"
#include "src/widgets/table/lv_table.c"
#include "src/widgets/tabview/lv_tabview.c"
#include "src/widgets/textarea/lv_textarea.c"
#include "src/widgets/tileview/lv_tileview.c"
#include "src/widgets/win/lv_win.c"
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl | repos/zig_workbench/BaseLVGL/lib/lvgl/src/lvgl_private.h | /**
* @file lvgl_private.h
*
*/
#ifndef LVGL_PRIVATE_H
#define LVGL_PRIVATE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "display/lv_display_private.h"
#include "indev/lv_indev_private.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LVGL_PRIVATE_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl | repos/zig_workbench/BaseLVGL/lib/lvgl/src/lv_api_map.h | /**
* @file lv_api_map.h
*
*/
#ifndef LV_API_MAP_H
#define LV_API_MAP_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lvgl.h"
/*********************
* DEFINES
*********************/
#define LV_DISP_ROTATION_0 LV_DISPLAY_ROTATION_0
#define LV_DISP_ROTATION_90 LV_DISPLAY_ROTATION_90
#define LV_DISP_ROTATION_180 LV_DISPLAY_ROTATION_180
#define LV_DISP_ROTATION_270 LV_DISPLAY_ROTATION_270
#define LV_DISP_RENDER_MODE_PARTIAL LV_DISPLAY_RENDER_MODE_PARTIAL
#define LV_DISP_RENDER_MODE_DIRECT LV_DISPLAY_RENDER_MODE_DIRECT
#define LV_DISP_RENDER_MODE_FULL LV_DISPLAY_RENDER_MODE_FULL
#define LV_BTNMATRIX_BTN_NONE LV_BUTTONMATRIX_BUTTON_NONE
#define LV_BTNMATRIX_CTRL_HIDDEN LV_BUTTONMATRIX_CTRL_HIDDEN
#define LV_BTNMATRIX_CTRL_NO_REPEAT LV_BUTTONMATRIX_CTRL_NO_REPEAT
#define LV_BTNMATRIX_CTRL_DISABLED LV_BUTTONMATRIX_CTRL_DISABLED
#define LV_BTNMATRIX_CTRL_CHECKABLE LV_BUTTONMATRIX_CTRL_CHECKABLE
#define LV_BTNMATRIX_CTRL_CHECKED LV_BUTTONMATRIX_CTRL_CHECKED
#define LV_BTNMATRIX_CTRL_CLICK_TRIG LV_BUTTONMATRIX_CTRL_CLICK_TRIG
#define LV_BTNMATRIX_CTRL_POPOVER LV_BUTTONMATRIX_CTRL_POPOVER
#define LV_BTNMATRIX_CTRL_RECOLOR LV_BUTTONMATRIX_CTRL_RECOLOR
#define LV_BTNMATRIX_CTRL_CUSTOM_1 LV_BUTTONMATRIX_CTRL_CUSTOM_1
#define LV_BTNMATRIX_CTRL_CUSTOM_2 LV_BUTTONMATRIX_CTRL_CUSTOM_2
/**********************
* TYPEDEFS
**********************/
typedef int32_t int32_t;
typedef lv_result_t lv_res_t;
typedef lv_image_dsc_t lv_img_dsc_t;
typedef lv_display_t lv_disp_t;
typedef lv_display_rotation_t lv_disp_rotation_t;
typedef lv_display_render_mode_t lv_disp_render_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
static inline LV_ATTRIBUTE_TIMER_HANDLER uint32_t lv_task_handler(void)
{
return lv_timer_handler();
}
/**
* Move the object to the foreground.
* It will look like if it was created as the last child of its parent.
* It also means it can cover any of the siblings.
* @param obj pointer to an object
*/
static inline void lv_obj_move_foreground(lv_obj_t * obj)
{
lv_obj_t * parent = lv_obj_get_parent(obj);
if(!parent) {
LV_LOG_WARN("parent is NULL");
return;
}
lv_obj_move_to_index(obj, lv_obj_get_child_cnt(parent) - 1);
}
/**
* Move the object to the background.
* It will look like if it was created as the first child of its parent.
* It also means any of the siblings can cover the object.
* @param obj pointer to an object
*/
static inline void lv_obj_move_background(lv_obj_t * obj)
{
lv_obj_move_to_index(obj, 0);
}
/**********************
* MACROS
**********************/
#define LV_RES_OK LV_RESULT_OK
#define LV_RES_INV LV_RESULT_INVALID
#define LV_INDEV_STATE_PR LV_INDEV_STATE_PRESSED
#define LV_INDEV_STATE_REL LV_INDEV_STATE_RELEASED
#define lv_obj_del lv_obj_delete
#define lv_obj_del_async lv_obj_delete_async
#define lv_obj_clear_flag lv_obj_remove_flag
#define lv_obj_clear_state lv_obj_remove_state
#define lv_indev_get_act lv_indev_active
#define lv_scr_act lv_screen_active
#define lv_disp_create lv_display_create
#define lv_disp_remove lv_display_remove
#define lv_disp_set_default lv_display_set_default
#define lv_disp_get_default lv_display_get_default
#define lv_disp_get_next lv_display_get_next
#define lv_disp_set_res lv_display_set_resolution
#define lv_disp_set_physical_res lv_display_set_physical_res
#define lv_disp_set_offset lv_display_set_offset
#define lv_disp_set_rotation lv_display_set_rotation
#define lv_disp_set_dpi lv_display_set_dpi
#define lv_disp_get_hor_res lv_display_get_horizontal_resolution
#define lv_disp_get_ver_res lv_display_get_vertical_resolution
#define lv_disp_get_physical_hor_res lv_display_get_physical_horizontal_resolution
#define lv_disp_get_physical_ver_res lv_display_get_physical_vertical_resolution
#define lv_disp_get_offset_x lv_display_get_offset_x
#define lv_disp_get_offset_y lv_display_get_offset_y
#define lv_disp_get_rotation lv_display_get_rotation
#define lv_disp_get_dpi lv_display_get_dpi
#define lv_disp_set_draw_buffers lv_display_set_draw_buffers
#define lv_disp_set_flush_cb lv_display_set_flush_cb
#define lv_disp_set_color_format lv_display_set_color_format
#define lv_disp_get_color_format lv_display_get_color_format
#define lv_disp_set_antialiasing lv_display_set_antialiasing
#define lv_disp_get_antialiasing lv_display_get_antialiasing
#define lv_disp_flush_ready lv_display_flush_ready
#define lv_disp_flush_is_last lv_display_flush_is_last
#define lv_disp_is_double_buffered lv_display_is_double_buffered
#define lv_disp_get_scr_act lv_display_get_screen_act
#define lv_disp_get_scr_prev lv_display_get_screen_prev
#define lv_disp_load_scr lv_display_load_scr
#define lv_disp_get_layer_top lv_display_get_layer_top
#define lv_disp_get_layer_sys lv_display_get_layer_sys
#define lv_disp_get_layer_bottom lv_display_get_layer_bottom
#define lv_disp_add_event lv_display_add_event
#define lv_disp_get_event_count lv_display_get_event_count
#define lv_disp_get_event_dsc lv_display_get_event_dsc
#define lv_disp_remove_event lv_display_remove_event
#define lv_disp_send_event lv_display_send_event
#define lv_disp_set_theme lv_display_set_theme
#define lv_disp_get_theme lv_display_get_theme
#define lv_disp_get_inactive_time lv_display_get_inactive_time
#define lv_disp_trig_activity lv_display_trig_activity
#define lv_disp_enable_invalidation lv_display_enable_invalidation
#define lv_disp_is_invalidation_enabled lv_display_is_invalidation_enabled
#define lv_disp_set_user_data lv_display_set_user_data
#define lv_disp_set_driver_data lv_display_set_driver_data
#define lv_disp_get_user_data lv_display_get_user_data
#define lv_disp_get_driver_data lv_display_get_driver_data
#define _lv_disp_refr_timer _lv_display_refr_timer
#define _lv_disp_get_refr_timer _lv_display_get_refr_timer
#define lv_disp_render_mode_t lv_display_render_mode_t
#define lv_timer_del lv_timer_delete
#define lv_anim_del lv_anim_delete
#define lv_anim_del_all lv_anim_delete_all
#define lv_group_del lv_group_delete
#define lv_txt_get_size lv_text_get_size
#define lv_txt_get_width lv_text_get_width
#define lv_img_create lv_image_create
#define lv_img_set_src lv_image_set_src
#define lv_img_set_offset_x lv_image_set_offset_x
#define lv_img_set_offset_y lv_image_set_offset_y
#define lv_img_set_angle lv_image_set_angle
#define lv_img_set_pivot lv_image_set_pivot
#define lv_img_set_zoom lv_image_set_zoom
#define lv_img_set_antialias lv_image_set_antialias
#define lv_img_set_size_mode lv_image_set_size_mode
#define lv_img_get_src lv_image_get_src
#define lv_img_get_offset_x lv_image_get_offset_x
#define lv_img_get_offset_y lv_image_get_offset_y
#define lv_img_get_angle lv_image_get_angle
#define lv_img_get_pivot lv_image_get_pivot
#define lv_img_get_zoom lv_image_get_zoom
#define lv_img_get_antialias lv_image_get_antialias
#define lv_img_get_size_mode lv_image_get_size_mode
#define lv_list_set_btn_text lv_list_set_button_text
#define lv_list_get_btn_text lv_list_get_button_text
#define lv_list_add_btn lv_list_add_button
#define lv_btn_create lv_button_create
#define lv_btnmatrix_create lv_buttonmatrix_create
#define lv_btnmatrix_set_map lv_buttonmatrix_set_map
#define lv_btnmatrix_set_ctrl_map lv_buttonmatrix_set_ctrl_map
#define lv_btnmatrix_set_selected_btn lv_buttonmatrix_set_selected_button
#define lv_btnmatrix_set_btn_ctrl lv_buttonmatrix_set_button_ctrl
#define lv_btnmatrix_clear_btn_ctrl lv_buttonmatrix_clear_button_ctrl
#define lv_btnmatrix_set_btn_ctrl_all lv_buttonmatrix_set_button_ctrl_all
#define lv_btnmatrix_clear_btn_ctrl_all lv_buttonmatrix_clear_button_ctrl_all
#define lv_btnmatrix_set_btn_width lv_buttonmatrix_set_button_width
#define lv_btnmatrix_set_one_checked lv_buttonmatrix_set_one_checked
#define lv_btnmatrix_get_map lv_buttonmatrix_get_map
#define lv_btnmatrix_get_selected_btn lv_buttonmatrix_get_selected_button
#define lv_btnmatrix_get_button_text lv_buttonmatrix_get_button_text
#define lv_btnmatrix_has_button_ctrl lv_buttonmatrix_has_button_ctrl
#define lv_btnmatrix_get_one_checked lv_buttonmatrix_get_one_checked
#define lv_tabview_get_tab_btns lv_tabview_get_tab_buttons
#define lv_tabview_get_act lv_tabview_get_active
#define lv_tabview_set_act lv_tabview_set_active
#define lv_tileview_get_tile_act lv_tileview_get_tile_active
#define lv_msgbox_get_btns lv_msgbox_get_buttons
#define lv_image_set_angle lv_image_set_rotation
#define lv_image_get_angle lv_image_get_rotation
#define lv_image_set_zoom lv_image_set_scale
#define lv_image_get_zoom lv_image_get_scale
#define lv_obj_get_style_shadow_ofs_x lv_obj_get_style_shadow_offset_x
#define lv_obj_get_style_shadow_ofs_y lv_obj_get_style_shadow_offset_y
#define lv_obj_get_style_transform_zoom lv_obj_get_style_transform_scale
#define lv_obj_get_style_transform_angle lv_obj_get_style_transform_rotation
#define lv_obj_set_style_shadow_ofs_x lv_obj_set_style_shadow_offset_x
#define lv_obj_set_style_shadow_ofs_y lv_obj_set_style_shadow_offset_y
#define lv_obj_set_style_transform_zoom lv_obj_set_style_transform_scale
#define lv_obj_set_style_transform_angle lv_obj_set_style_transform_rotation
#define lv_style_set_shadow_ofs_x lv_style_set_shadow_offset_x
#define lv_style_set_shadow_ofs_y lv_style_set_shadow_offset_y
#define lv_style_set_transform_angle lv_style_set_transform_rotation
#define lv_style_set_transform_zoom lv_style_set_transform_scale
#define LV_ZOOM_NONE LV_SCALE_NONE
/**********************
* MACROS
**********************/
/** Use this macro to declare an image in a C file*/
#define LV_IMG_DECLARE(var_name) extern const lv_image_dsc_t var_name;
/**********************
* DEPRECATED FUNCTIONS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_API_MAP_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl | repos/zig_workbench/BaseLVGL/lib/lvgl/src/lv_conf_internal.h | /**
* GENERATED FILE, DO NOT EDIT IT!
* @file lv_conf_internal.h
* Make sure all the defines of lv_conf.h have a default value
**/
#ifndef LV_CONF_INTERNAL_H
#define LV_CONF_INTERNAL_H
/* clang-format off */
#include "misc/lv_types.h"
/* Handle special Kconfig options */
#ifndef LV_KCONFIG_IGNORE
#include "lv_conf_kconfig.h"
#ifdef CONFIG_LV_CONF_SKIP
#define LV_CONF_SKIP
#endif
#endif
/*If "lv_conf.h" is available from here try to use it later.*/
#ifdef __has_include
#if __has_include("lv_conf.h")
#ifndef LV_CONF_INCLUDE_SIMPLE
#define LV_CONF_INCLUDE_SIMPLE
#endif
#endif
#endif
/*If lv_conf.h is not skipped include it*/
#ifndef LV_CONF_SKIP
#ifdef LV_CONF_PATH /*If there is a path defined for lv_conf.h use it*/
#define __LV_TO_STR_AUX(x) #x
#define __LV_TO_STR(x) __LV_TO_STR_AUX(x)
#include __LV_TO_STR(LV_CONF_PATH)
#undef __LV_TO_STR_AUX
#undef __LV_TO_STR
#elif defined(LV_CONF_INCLUDE_SIMPLE) /*Or simply include lv_conf.h is enabled*/
#include "lv_conf.h"
#else
#include "../lv_conf.h" /*Else assume lv_conf.h is next to the lvgl folder*/
#endif
#if !defined(LV_CONF_H) && !defined(LV_CONF_SUPPRESS_DEFINE_CHECK)
/* #include will sometimes silently fail when __has_include is used */
/* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80753 */
#pragma message("Possible failure to include lv_conf.h, please read the comment in this file if you get errors")
#endif
#endif
#ifdef CONFIG_LV_COLOR_DEPTH
#define _LV_KCONFIG_PRESENT
#endif
/*----------------------------------
* Start parsing lv_conf_template.h
-----------------------------------*/
#include <stdint.h>
/*====================
COLOR SETTINGS
*====================*/
/*Color depth: 8 (A8), 16 (RGB565), 24 (RGB888), 32 (XRGB8888)*/
#ifndef LV_COLOR_DEPTH
#ifdef CONFIG_LV_COLOR_DEPTH
#define LV_COLOR_DEPTH CONFIG_LV_COLOR_DEPTH
#else
#define LV_COLOR_DEPTH 16
#endif
#endif
/*=========================
STDLIB WRAPPER SETTINGS
*=========================*/
/* Possible values
* - LV_STDLIB_BUILTIN: LVGL's built in implementation
* - LV_STDLIB_CLIB: Standard C functions, like malloc, strlen, etc
* - LV_STDLIB_MICROPYTHON: MicroPython implementation
* - LV_STDLIB_CUSTOM: Implement the functions externally
*/
#ifndef LV_USE_STDLIB_MALLOC
#ifdef CONFIG_LV_USE_STDLIB_MALLOC
#define LV_USE_STDLIB_MALLOC CONFIG_LV_USE_STDLIB_MALLOC
#else
#define LV_USE_STDLIB_MALLOC LV_STDLIB_BUILTIN
#endif
#endif
#ifndef LV_USE_STDLIB_STRING
#ifdef CONFIG_LV_USE_STDLIB_STRING
#define LV_USE_STDLIB_STRING CONFIG_LV_USE_STDLIB_STRING
#else
#define LV_USE_STDLIB_STRING LV_STDLIB_BUILTIN
#endif
#endif
#ifndef LV_USE_STDLIB_SPRINTF
#ifdef CONFIG_LV_USE_STDLIB_SPRINTF
#define LV_USE_STDLIB_SPRINTF CONFIG_LV_USE_STDLIB_SPRINTF
#else
#define LV_USE_STDLIB_SPRINTF LV_STDLIB_BUILTIN
#endif
#endif
#if LV_USE_STDLIB_MALLOC == LV_STDLIB_BUILTIN
/*Size of the memory available for `lv_malloc()` in bytes (>= 2kB)*/
#ifndef LV_MEM_SIZE
#ifdef CONFIG_LV_MEM_SIZE
#define LV_MEM_SIZE CONFIG_LV_MEM_SIZE
#else
#define LV_MEM_SIZE (256 * 1024U) /*[bytes]*/
#endif
#endif
/*Size of the memory expand for `lv_malloc()` in bytes*/
#ifndef LV_MEM_POOL_EXPAND_SIZE
#ifdef CONFIG_LV_MEM_POOL_EXPAND_SIZE
#define LV_MEM_POOL_EXPAND_SIZE CONFIG_LV_MEM_POOL_EXPAND_SIZE
#else
#define LV_MEM_POOL_EXPAND_SIZE 0
#endif
#endif
/*Set an address for the memory pool instead of allocating it as a normal array. Can be in external SRAM too.*/
#ifndef LV_MEM_ADR
#ifdef CONFIG_LV_MEM_ADR
#define LV_MEM_ADR CONFIG_LV_MEM_ADR
#else
#define LV_MEM_ADR 0 /*0: unused*/
#endif
#endif
/*Instead of an address give a memory allocator that will be called to get a memory pool for LVGL. E.g. my_malloc*/
#if LV_MEM_ADR == 0
#ifndef LV_MEM_POOL_INCLUDE
#ifdef CONFIG_LV_MEM_POOL_INCLUDE
#define LV_MEM_POOL_INCLUDE CONFIG_LV_MEM_POOL_INCLUDE
#else
#undef LV_MEM_POOL_INCLUDE
#endif
#endif
#ifndef LV_MEM_POOL_ALLOC
#ifdef CONFIG_LV_MEM_POOL_ALLOC
#define LV_MEM_POOL_ALLOC CONFIG_LV_MEM_POOL_ALLOC
#else
#undef LV_MEM_POOL_ALLOC
#endif
#endif
#endif
#endif /*LV_USE_MALLOC == LV_STDLIB_BUILTIN*/
/*====================
HAL SETTINGS
*====================*/
/*Default display refresh, input device read and animation step period.*/
#ifndef LV_DEF_REFR_PERIOD
#ifdef CONFIG_LV_DEF_REFR_PERIOD
#define LV_DEF_REFR_PERIOD CONFIG_LV_DEF_REFR_PERIOD
#else
#define LV_DEF_REFR_PERIOD 33 /*[ms]*/
#endif
#endif
/*Default Dot Per Inch. Used to initialize default sizes such as widgets sized, style paddings.
*(Not so important, you can adjust it to modify default sizes and spaces)*/
#ifndef LV_DPI_DEF
#ifdef CONFIG_LV_DPI_DEF
#define LV_DPI_DEF CONFIG_LV_DPI_DEF
#else
#define LV_DPI_DEF 130 /*[px/inch]*/
#endif
#endif
/*========================
* RENDERING CONFIGURATION
*========================*/
/*Align the stride of all layers and images to this bytes*/
#ifndef LV_DRAW_BUF_STRIDE_ALIGN
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_DRAW_BUF_STRIDE_ALIGN
#define LV_DRAW_BUF_STRIDE_ALIGN CONFIG_LV_DRAW_BUF_STRIDE_ALIGN
#else
#define LV_DRAW_BUF_STRIDE_ALIGN 0
#endif
#else
#define LV_DRAW_BUF_STRIDE_ALIGN 1
#endif
#endif
/*Align the start address of draw_buf addresses to this bytes*/
#ifndef LV_DRAW_BUF_ALIGN
#ifdef CONFIG_LV_DRAW_BUF_ALIGN
#define LV_DRAW_BUF_ALIGN CONFIG_LV_DRAW_BUF_ALIGN
#else
#define LV_DRAW_BUF_ALIGN 4
#endif
#endif
/* Max. memory to be used for layers */
#ifndef LV_LAYER_MAX_MEMORY_USAGE
#ifdef CONFIG_LV_LAYER_MAX_MEMORY_USAGE
#define LV_LAYER_MAX_MEMORY_USAGE CONFIG_LV_LAYER_MAX_MEMORY_USAGE
#else
#define LV_LAYER_MAX_MEMORY_USAGE 150 /*[kB]*/
#endif
#endif
#ifndef LV_USE_DRAW_SW
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_DRAW_SW
#define LV_USE_DRAW_SW CONFIG_LV_USE_DRAW_SW
#else
#define LV_USE_DRAW_SW 0
#endif
#else
#define LV_USE_DRAW_SW 1
#endif
#endif
#if LV_USE_DRAW_SW == 1
/* Set the number of draw unit.
* > 1 requires an operating system enabled in `LV_USE_OS`
* > 1 means multiply threads will render the screen in parallel */
#ifndef LV_DRAW_SW_DRAW_UNIT_CNT
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT
#define LV_DRAW_SW_DRAW_UNIT_CNT CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT
#else
#define LV_DRAW_SW_DRAW_UNIT_CNT 0
#endif
#else
#define LV_DRAW_SW_DRAW_UNIT_CNT 1
#endif
#endif
/* If a widget has `style_opa < 255` (not `bg_opa`, `text_opa` etc) or not NORMAL blend mode
* it is buffered into a "simple" layer before rendering. The widget can be buffered in smaller chunks.
* "Transformed layers" (if `transform_angle/zoom` are set) use larger buffers
* and can't be drawn in chunks. */
/*The target buffer size for simple layer chunks.*/
#ifndef LV_DRAW_SW_LAYER_SIMPLE_BUF_SIZE
#ifdef CONFIG_LV_DRAW_SW_LAYER_SIMPLE_BUF_SIZE
#define LV_DRAW_SW_LAYER_SIMPLE_BUF_SIZE CONFIG_LV_DRAW_SW_LAYER_SIMPLE_BUF_SIZE
#else
#define LV_DRAW_SW_LAYER_SIMPLE_BUF_SIZE (24 * 1024) /*[bytes]*/
#endif
#endif
/* 0: use a simple renderer capable of drawing only simple rectangles with gradient, images, texts, and straight lines only
* 1: use a complex renderer capable of drawing rounded corners, shadow, skew lines, and arcs too */
#ifndef LV_DRAW_SW_COMPLEX
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_DRAW_SW_COMPLEX
#define LV_DRAW_SW_COMPLEX CONFIG_LV_DRAW_SW_COMPLEX
#else
#define LV_DRAW_SW_COMPLEX 0
#endif
#else
#define LV_DRAW_SW_COMPLEX 1
#endif
#endif
#if LV_DRAW_SW_COMPLEX == 1
/*Allow buffering some shadow calculation.
*LV_DRAW_SW_SHADOW_CACHE_SIZE is the max. shadow size to buffer, where shadow size is `shadow_width + radius`
*Caching has LV_DRAW_SW_SHADOW_CACHE_SIZE^2 RAM cost*/
#ifndef LV_DRAW_SW_SHADOW_CACHE_SIZE
#ifdef CONFIG_LV_DRAW_SW_SHADOW_CACHE_SIZE
#define LV_DRAW_SW_SHADOW_CACHE_SIZE CONFIG_LV_DRAW_SW_SHADOW_CACHE_SIZE
#else
#define LV_DRAW_SW_SHADOW_CACHE_SIZE 0
#endif
#endif
/* Set number of maximally cached circle data.
* The circumference of 1/4 circle are saved for anti-aliasing
* radius * 4 bytes are used per circle (the most often used radiuses are saved)
* 0: to disable caching */
#ifndef LV_DRAW_SW_CIRCLE_CACHE_SIZE
#ifdef CONFIG_LV_DRAW_SW_CIRCLE_CACHE_SIZE
#define LV_DRAW_SW_CIRCLE_CACHE_SIZE CONFIG_LV_DRAW_SW_CIRCLE_CACHE_SIZE
#else
#define LV_DRAW_SW_CIRCLE_CACHE_SIZE 4
#endif
#endif
#endif
#ifndef LV_USE_DRAW_SW_ASM
#ifdef CONFIG_LV_USE_DRAW_SW_ASM
#define LV_USE_DRAW_SW_ASM CONFIG_LV_USE_DRAW_SW_ASM
#else
#define LV_USE_DRAW_SW_ASM LV_DRAW_SW_ASM_NONE
#endif
#endif
#if LV_USE_DRAW_SW_ASM == LV_DRAW_SW_ASM_CUSTOM
#ifndef LV_DRAW_SW_ASM_CUSTOM_INCLUDE
#ifdef CONFIG_LV_DRAW_SW_ASM_CUSTOM_INCLUDE
#define LV_DRAW_SW_ASM_CUSTOM_INCLUDE CONFIG_LV_DRAW_SW_ASM_CUSTOM_INCLUDE
#else
#define LV_DRAW_SW_ASM_CUSTOM_INCLUDE ""
#endif
#endif
#endif
#endif
/* Use NXP's VG-Lite GPU on iMX RTxxx platforms. */
#ifndef LV_USE_DRAW_VGLITE
#ifdef CONFIG_LV_USE_DRAW_VGLITE
#define LV_USE_DRAW_VGLITE CONFIG_LV_USE_DRAW_VGLITE
#else
#define LV_USE_DRAW_VGLITE 0
#endif
#endif
/* Use NXP's PXP on iMX RTxxx platforms. */
#ifndef LV_USE_DRAW_PXP
#ifdef CONFIG_LV_USE_DRAW_PXP
#define LV_USE_DRAW_PXP CONFIG_LV_USE_DRAW_PXP
#else
#define LV_USE_DRAW_PXP 0
#endif
#endif
/*=================
* OPERATING SYSTEM
*=================*/
/*Select an operating system to use. Possible options:
* - LV_OS_NONE
* - LV_OS_PTHREAD
* - LV_OS_FREERTOS
* - LV_OS_CMSIS_RTOS2
* - LV_OS_RTTHREAD
* - LV_OS_CUSTOM */
#ifndef LV_USE_OS
#ifdef CONFIG_LV_USE_OS
#define LV_USE_OS CONFIG_LV_USE_OS
#else
#define LV_USE_OS LV_OS_NONE
#endif
#endif
#if LV_USE_OS == LV_OS_CUSTOM
#ifndef LV_OS_CUSTOM_INCLUDE
#ifdef CONFIG_LV_OS_CUSTOM_INCLUDE
#define LV_OS_CUSTOM_INCLUDE CONFIG_LV_OS_CUSTOM_INCLUDE
#else
#define LV_OS_CUSTOM_INCLUDE <stdint.h>
#endif
#endif
#endif
/*=======================
* FEATURE CONFIGURATION
*=======================*/
/*-------------
* Logging
*-----------*/
/*Enable the log module*/
#ifndef LV_USE_LOG
#ifdef CONFIG_LV_USE_LOG
#define LV_USE_LOG CONFIG_LV_USE_LOG
#else
#define LV_USE_LOG 0
#endif
#endif
#if LV_USE_LOG
/*How important log should be added:
*LV_LOG_LEVEL_TRACE A lot of logs to give detailed information
*LV_LOG_LEVEL_INFO Log important events
*LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't cause a problem
*LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail
*LV_LOG_LEVEL_USER Only logs added by the user
*LV_LOG_LEVEL_NONE Do not log anything*/
#ifndef LV_LOG_LEVEL
#ifdef CONFIG_LV_LOG_LEVEL
#define LV_LOG_LEVEL CONFIG_LV_LOG_LEVEL
#else
#define LV_LOG_LEVEL LV_LOG_LEVEL_WARN
#endif
#endif
/*1: Print the log with 'printf';
*0: User need to register a callback with `lv_log_register_print_cb()`*/
#ifndef LV_LOG_PRINTF
#ifdef CONFIG_LV_LOG_PRINTF
#define LV_LOG_PRINTF CONFIG_LV_LOG_PRINTF
#else
#define LV_LOG_PRINTF 0
#endif
#endif
/*1: Enable print timestamp;
*0: Disable print timestamp*/
#ifndef LV_LOG_USE_TIMESTAMP
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_LOG_USE_TIMESTAMP
#define LV_LOG_USE_TIMESTAMP CONFIG_LV_LOG_USE_TIMESTAMP
#else
#define LV_LOG_USE_TIMESTAMP 0
#endif
#else
#define LV_LOG_USE_TIMESTAMP 1
#endif
#endif
/*1: Print file and line number of the log;
*0: Do not print file and line number of the log*/
#ifndef LV_LOG_USE_FILE_LINE
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_LOG_USE_FILE_LINE
#define LV_LOG_USE_FILE_LINE CONFIG_LV_LOG_USE_FILE_LINE
#else
#define LV_LOG_USE_FILE_LINE 0
#endif
#else
#define LV_LOG_USE_FILE_LINE 1
#endif
#endif
/*Enable/disable LV_LOG_TRACE in modules that produces a huge number of logs*/
#ifndef LV_LOG_TRACE_MEM
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_LOG_TRACE_MEM
#define LV_LOG_TRACE_MEM CONFIG_LV_LOG_TRACE_MEM
#else
#define LV_LOG_TRACE_MEM 0
#endif
#else
#define LV_LOG_TRACE_MEM 1
#endif
#endif
#ifndef LV_LOG_TRACE_TIMER
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_LOG_TRACE_TIMER
#define LV_LOG_TRACE_TIMER CONFIG_LV_LOG_TRACE_TIMER
#else
#define LV_LOG_TRACE_TIMER 0
#endif
#else
#define LV_LOG_TRACE_TIMER 1
#endif
#endif
#ifndef LV_LOG_TRACE_INDEV
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_LOG_TRACE_INDEV
#define LV_LOG_TRACE_INDEV CONFIG_LV_LOG_TRACE_INDEV
#else
#define LV_LOG_TRACE_INDEV 0
#endif
#else
#define LV_LOG_TRACE_INDEV 1
#endif
#endif
#ifndef LV_LOG_TRACE_DISP_REFR
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_LOG_TRACE_DISP_REFR
#define LV_LOG_TRACE_DISP_REFR CONFIG_LV_LOG_TRACE_DISP_REFR
#else
#define LV_LOG_TRACE_DISP_REFR 0
#endif
#else
#define LV_LOG_TRACE_DISP_REFR 1
#endif
#endif
#ifndef LV_LOG_TRACE_EVENT
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_LOG_TRACE_EVENT
#define LV_LOG_TRACE_EVENT CONFIG_LV_LOG_TRACE_EVENT
#else
#define LV_LOG_TRACE_EVENT 0
#endif
#else
#define LV_LOG_TRACE_EVENT 1
#endif
#endif
#ifndef LV_LOG_TRACE_OBJ_CREATE
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_LOG_TRACE_OBJ_CREATE
#define LV_LOG_TRACE_OBJ_CREATE CONFIG_LV_LOG_TRACE_OBJ_CREATE
#else
#define LV_LOG_TRACE_OBJ_CREATE 0
#endif
#else
#define LV_LOG_TRACE_OBJ_CREATE 1
#endif
#endif
#ifndef LV_LOG_TRACE_LAYOUT
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_LOG_TRACE_LAYOUT
#define LV_LOG_TRACE_LAYOUT CONFIG_LV_LOG_TRACE_LAYOUT
#else
#define LV_LOG_TRACE_LAYOUT 0
#endif
#else
#define LV_LOG_TRACE_LAYOUT 1
#endif
#endif
#ifndef LV_LOG_TRACE_ANIM
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_LOG_TRACE_ANIM
#define LV_LOG_TRACE_ANIM CONFIG_LV_LOG_TRACE_ANIM
#else
#define LV_LOG_TRACE_ANIM 0
#endif
#else
#define LV_LOG_TRACE_ANIM 1
#endif
#endif
#ifndef LV_LOG_TRACE_CACHE
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_LOG_TRACE_CACHE
#define LV_LOG_TRACE_CACHE CONFIG_LV_LOG_TRACE_CACHE
#else
#define LV_LOG_TRACE_CACHE 0
#endif
#else
#define LV_LOG_TRACE_CACHE 1
#endif
#endif
#endif /*LV_USE_LOG*/
/*-------------
* Asserts
*-----------*/
/*Enable asserts if an operation is failed or an invalid data is found.
*If LV_USE_LOG is enabled an error message will be printed on failure*/
#ifndef LV_USE_ASSERT_NULL
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_ASSERT_NULL
#define LV_USE_ASSERT_NULL CONFIG_LV_USE_ASSERT_NULL
#else
#define LV_USE_ASSERT_NULL 0
#endif
#else
#define LV_USE_ASSERT_NULL 1 /*Check if the parameter is NULL. (Very fast, recommended)*/
#endif
#endif
#ifndef LV_USE_ASSERT_MALLOC
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_ASSERT_MALLOC
#define LV_USE_ASSERT_MALLOC CONFIG_LV_USE_ASSERT_MALLOC
#else
#define LV_USE_ASSERT_MALLOC 0
#endif
#else
#define LV_USE_ASSERT_MALLOC 1 /*Checks is the memory is successfully allocated or no. (Very fast, recommended)*/
#endif
#endif
#ifndef LV_USE_ASSERT_STYLE
#ifdef CONFIG_LV_USE_ASSERT_STYLE
#define LV_USE_ASSERT_STYLE CONFIG_LV_USE_ASSERT_STYLE
#else
#define LV_USE_ASSERT_STYLE 0 /*Check if the styles are properly initialized. (Very fast, recommended)*/
#endif
#endif
#ifndef LV_USE_ASSERT_MEM_INTEGRITY
#ifdef CONFIG_LV_USE_ASSERT_MEM_INTEGRITY
#define LV_USE_ASSERT_MEM_INTEGRITY CONFIG_LV_USE_ASSERT_MEM_INTEGRITY
#else
#define LV_USE_ASSERT_MEM_INTEGRITY 0 /*Check the integrity of `lv_mem` after critical operations. (Slow)*/
#endif
#endif
#ifndef LV_USE_ASSERT_OBJ
#ifdef CONFIG_LV_USE_ASSERT_OBJ
#define LV_USE_ASSERT_OBJ CONFIG_LV_USE_ASSERT_OBJ
#else
#define LV_USE_ASSERT_OBJ 0 /*Check the object's type and existence (e.g. not deleted). (Slow)*/
#endif
#endif
/*Add a custom handler when assert happens e.g. to restart the MCU*/
#ifndef LV_ASSERT_HANDLER_INCLUDE
#ifdef CONFIG_LV_ASSERT_HANDLER_INCLUDE
#define LV_ASSERT_HANDLER_INCLUDE CONFIG_LV_ASSERT_HANDLER_INCLUDE
#else
#define LV_ASSERT_HANDLER_INCLUDE <stdint.h>
#endif
#endif
#ifndef LV_ASSERT_HANDLER
#ifdef CONFIG_LV_ASSERT_HANDLER
#define LV_ASSERT_HANDLER CONFIG_LV_ASSERT_HANDLER
#else
#define LV_ASSERT_HANDLER while(1); /*Halt by default*/
#endif
#endif
/*-------------
* Debug
*-----------*/
/*1: Draw random colored rectangles over the redrawn areas*/
#ifndef LV_USE_REFR_DEBUG
#ifdef CONFIG_LV_USE_REFR_DEBUG
#define LV_USE_REFR_DEBUG CONFIG_LV_USE_REFR_DEBUG
#else
#define LV_USE_REFR_DEBUG 0
#endif
#endif
/*1: Draw a red overlay for ARGB layers and a green overlay for RGB layers*/
#ifndef LV_USE_LAYER_DEBUG
#ifdef CONFIG_LV_USE_LAYER_DEBUG
#define LV_USE_LAYER_DEBUG CONFIG_LV_USE_LAYER_DEBUG
#else
#define LV_USE_LAYER_DEBUG 0
#endif
#endif
/*1: Draw overlays with different colors for each draw_unit's tasks.
*Also add the index number of the draw unit on white background.
*For layers add the index number of the draw unit on black background.*/
#ifndef LV_USE_PARALLEL_DRAW_DEBUG
#ifdef CONFIG_LV_USE_PARALLEL_DRAW_DEBUG
#define LV_USE_PARALLEL_DRAW_DEBUG CONFIG_LV_USE_PARALLEL_DRAW_DEBUG
#else
#define LV_USE_PARALLEL_DRAW_DEBUG 0
#endif
#endif
/*------------------
* STATUS MONITORING
*------------------*/
/*1: Show CPU usage and FPS count
* Requires `LV_USE_SYSMON = 1`*/
#ifndef LV_USE_PERF_MONITOR
#ifdef CONFIG_LV_USE_PERF_MONITOR
#define LV_USE_PERF_MONITOR CONFIG_LV_USE_PERF_MONITOR
#else
#define LV_USE_PERF_MONITOR 0
#endif
#endif
#if LV_USE_PERF_MONITOR
#ifndef LV_USE_PERF_MONITOR_POS
#ifdef CONFIG_LV_USE_PERF_MONITOR_POS
#define LV_USE_PERF_MONITOR_POS CONFIG_LV_USE_PERF_MONITOR_POS
#else
#define LV_USE_PERF_MONITOR_POS LV_ALIGN_BOTTOM_RIGHT
#endif
#endif
/*0: Displays performance data on the screen, 1: Prints performance data using log.*/
#ifndef LV_USE_PERF_MONITOR_LOG_MODE
#ifdef CONFIG_LV_USE_PERF_MONITOR_LOG_MODE
#define LV_USE_PERF_MONITOR_LOG_MODE CONFIG_LV_USE_PERF_MONITOR_LOG_MODE
#else
#define LV_USE_PERF_MONITOR_LOG_MODE 0
#endif
#endif
#endif
/*1: Show the used memory and the memory fragmentation
* Requires `LV_USE_BUILTIN_MALLOC = 1`
* Requires `LV_USE_SYSMON = 1`*/
#ifndef LV_USE_MEM_MONITOR
#ifdef CONFIG_LV_USE_MEM_MONITOR
#define LV_USE_MEM_MONITOR CONFIG_LV_USE_MEM_MONITOR
#else
#define LV_USE_MEM_MONITOR 0
#endif
#endif
#if LV_USE_MEM_MONITOR
#ifndef LV_USE_MEM_MONITOR_POS
#ifdef CONFIG_LV_USE_MEM_MONITOR_POS
#define LV_USE_MEM_MONITOR_POS CONFIG_LV_USE_MEM_MONITOR_POS
#else
#define LV_USE_MEM_MONITOR_POS LV_ALIGN_BOTTOM_LEFT
#endif
#endif
#endif
/*-------------
* Others
*-----------*/
/*Maximum buffer size to allocate for rotation.
*Only used if software rotation is enabled in the display driver.*/
#ifndef LV_DISPLAY_ROT_MAX_BUF
#ifdef CONFIG_LV_DISPLAY_ROT_MAX_BUF
#define LV_DISPLAY_ROT_MAX_BUF CONFIG_LV_DISPLAY_ROT_MAX_BUF
#else
#define LV_DISPLAY_ROT_MAX_BUF (10*1024)
#endif
#endif
#ifndef LV_ENABLE_GLOBAL_CUSTOM
#ifdef CONFIG_LV_ENABLE_GLOBAL_CUSTOM
#define LV_ENABLE_GLOBAL_CUSTOM CONFIG_LV_ENABLE_GLOBAL_CUSTOM
#else
#define LV_ENABLE_GLOBAL_CUSTOM 0
#endif
#endif
#if LV_ENABLE_GLOBAL_CUSTOM
/*Header to include for the custom 'lv_global' function"*/
#ifndef LV_GLOBAL_CUSTOM_INCLUDE
#ifdef CONFIG_LV_GLOBAL_CUSTOM_INCLUDE
#define LV_GLOBAL_CUSTOM_INCLUDE CONFIG_LV_GLOBAL_CUSTOM_INCLUDE
#else
#define LV_GLOBAL_CUSTOM_INCLUDE <stdint.h>
#endif
#endif
#endif
/*Default cache size in bytes.
*Used by image decoders such as `lv_lodepng` to keep the decoded image in the memory.
*Data larger than the size of the cache also can be allocated but
*will be dropped immediately after usage.*/
#ifndef LV_CACHE_DEF_SIZE
#ifdef CONFIG_LV_CACHE_DEF_SIZE
#define LV_CACHE_DEF_SIZE CONFIG_LV_CACHE_DEF_SIZE
#else
#define LV_CACHE_DEF_SIZE 0
#endif
#endif
/*Number of stops allowed per gradient. Increase this to allow more stops.
*This adds (sizeof(lv_color_t) + 1) bytes per additional stop*/
#ifndef LV_GRADIENT_MAX_STOPS
#ifdef CONFIG_LV_GRADIENT_MAX_STOPS
#define LV_GRADIENT_MAX_STOPS CONFIG_LV_GRADIENT_MAX_STOPS
#else
#define LV_GRADIENT_MAX_STOPS 2
#endif
#endif
/* Adjust color mix functions rounding. GPUs might calculate color mix (blending) differently.
* 0: round down, 64: round up from x.75, 128: round up from half, 192: round up from x.25, 254: round up */
#ifndef LV_COLOR_MIX_ROUND_OFS
#ifdef CONFIG_LV_COLOR_MIX_ROUND_OFS
#define LV_COLOR_MIX_ROUND_OFS CONFIG_LV_COLOR_MIX_ROUND_OFS
#else
#define LV_COLOR_MIX_ROUND_OFS 0
#endif
#endif
/* Add 2 x 32 bit variables to each lv_obj_t to speed up getting style properties */
#ifndef LV_OBJ_STYLE_CACHE
#ifdef CONFIG_LV_OBJ_STYLE_CACHE
#define LV_OBJ_STYLE_CACHE CONFIG_LV_OBJ_STYLE_CACHE
#else
#define LV_OBJ_STYLE_CACHE 0
#endif
#endif
/* Add `id` field to `lv_obj_t` */
#ifndef LV_USE_OBJ_ID
#ifdef CONFIG_LV_USE_OBJ_ID
#define LV_USE_OBJ_ID CONFIG_LV_USE_OBJ_ID
#else
#define LV_USE_OBJ_ID 0
#endif
#endif
/* Use lvgl builtin method for obj ID */
#ifndef LV_USE_OBJ_ID_BUILTIN
#ifdef CONFIG_LV_USE_OBJ_ID_BUILTIN
#define LV_USE_OBJ_ID_BUILTIN CONFIG_LV_USE_OBJ_ID_BUILTIN
#else
#define LV_USE_OBJ_ID_BUILTIN 0
#endif
#endif
/*Use obj property set/get API*/
#ifndef LV_USE_OBJ_PROPERTY
#ifdef CONFIG_LV_USE_OBJ_PROPERTY
#define LV_USE_OBJ_PROPERTY CONFIG_LV_USE_OBJ_PROPERTY
#else
#define LV_USE_OBJ_PROPERTY 0
#endif
#endif
/*=====================
* COMPILER SETTINGS
*====================*/
/*For big endian systems set to 1*/
#ifndef LV_BIG_ENDIAN_SYSTEM
#ifdef CONFIG_LV_BIG_ENDIAN_SYSTEM
#define LV_BIG_ENDIAN_SYSTEM CONFIG_LV_BIG_ENDIAN_SYSTEM
#else
#define LV_BIG_ENDIAN_SYSTEM 0
#endif
#endif
/*Define a custom attribute to `lv_tick_inc` function*/
#ifndef LV_ATTRIBUTE_TICK_INC
#ifdef CONFIG_LV_ATTRIBUTE_TICK_INC
#define LV_ATTRIBUTE_TICK_INC CONFIG_LV_ATTRIBUTE_TICK_INC
#else
#define LV_ATTRIBUTE_TICK_INC
#endif
#endif
/*Define a custom attribute to `lv_timer_handler` function*/
#ifndef LV_ATTRIBUTE_TIMER_HANDLER
#ifdef CONFIG_LV_ATTRIBUTE_TIMER_HANDLER
#define LV_ATTRIBUTE_TIMER_HANDLER CONFIG_LV_ATTRIBUTE_TIMER_HANDLER
#else
#define LV_ATTRIBUTE_TIMER_HANDLER
#endif
#endif
/*Define a custom attribute to `lv_display_flush_ready` function*/
#ifndef LV_ATTRIBUTE_FLUSH_READY
#ifdef CONFIG_LV_ATTRIBUTE_FLUSH_READY
#define LV_ATTRIBUTE_FLUSH_READY CONFIG_LV_ATTRIBUTE_FLUSH_READY
#else
#define LV_ATTRIBUTE_FLUSH_READY
#endif
#endif
/*Required alignment size for buffers*/
#ifndef LV_ATTRIBUTE_MEM_ALIGN_SIZE
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_ATTRIBUTE_MEM_ALIGN_SIZE
#define LV_ATTRIBUTE_MEM_ALIGN_SIZE CONFIG_LV_ATTRIBUTE_MEM_ALIGN_SIZE
#else
#define LV_ATTRIBUTE_MEM_ALIGN_SIZE 0
#endif
#else
#define LV_ATTRIBUTE_MEM_ALIGN_SIZE 1
#endif
#endif
/*Will be added where memories needs to be aligned (with -Os data might not be aligned to boundary by default).
* E.g. __attribute__((aligned(4)))*/
#ifndef LV_ATTRIBUTE_MEM_ALIGN
#ifdef CONFIG_LV_ATTRIBUTE_MEM_ALIGN
#define LV_ATTRIBUTE_MEM_ALIGN CONFIG_LV_ATTRIBUTE_MEM_ALIGN
#else
#define LV_ATTRIBUTE_MEM_ALIGN
#endif
#endif
/*Attribute to mark large constant arrays for example font's bitmaps*/
#ifndef LV_ATTRIBUTE_LARGE_CONST
#ifdef CONFIG_LV_ATTRIBUTE_LARGE_CONST
#define LV_ATTRIBUTE_LARGE_CONST CONFIG_LV_ATTRIBUTE_LARGE_CONST
#else
#define LV_ATTRIBUTE_LARGE_CONST
#endif
#endif
/*Compiler prefix for a big array declaration in RAM*/
#ifndef LV_ATTRIBUTE_LARGE_RAM_ARRAY
#ifdef CONFIG_LV_ATTRIBUTE_LARGE_RAM_ARRAY
#define LV_ATTRIBUTE_LARGE_RAM_ARRAY CONFIG_LV_ATTRIBUTE_LARGE_RAM_ARRAY
#else
#define LV_ATTRIBUTE_LARGE_RAM_ARRAY
#endif
#endif
/*Place performance critical functions into a faster memory (e.g RAM)*/
#ifndef LV_ATTRIBUTE_FAST_MEM
#ifdef CONFIG_LV_ATTRIBUTE_FAST_MEM
#define LV_ATTRIBUTE_FAST_MEM CONFIG_LV_ATTRIBUTE_FAST_MEM
#else
#define LV_ATTRIBUTE_FAST_MEM
#endif
#endif
/*Export integer constant to binding. This macro is used with constants in the form of LV_<CONST> that
*should also appear on LVGL binding API such as Micropython.*/
#ifndef LV_EXPORT_CONST_INT
#ifdef CONFIG_LV_EXPORT_CONST_INT
#define LV_EXPORT_CONST_INT CONFIG_LV_EXPORT_CONST_INT
#else
#define LV_EXPORT_CONST_INT(int_value) struct _silence_gcc_warning /*The default value just prevents GCC warning*/
#endif
#endif
/* Use `float` as `lv_value_precise_t` */
#ifndef LV_USE_FLOAT
#ifdef CONFIG_LV_USE_FLOAT
#define LV_USE_FLOAT CONFIG_LV_USE_FLOAT
#else
#define LV_USE_FLOAT 0
#endif
#endif
/*==================
* FONT USAGE
*===================*/
/*Montserrat fonts with ASCII range and some symbols using bpp = 4
*https://fonts.google.com/specimen/Montserrat*/
#ifndef LV_FONT_MONTSERRAT_8
#ifdef CONFIG_LV_FONT_MONTSERRAT_8
#define LV_FONT_MONTSERRAT_8 CONFIG_LV_FONT_MONTSERRAT_8
#else
#define LV_FONT_MONTSERRAT_8 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_10
#ifdef CONFIG_LV_FONT_MONTSERRAT_10
#define LV_FONT_MONTSERRAT_10 CONFIG_LV_FONT_MONTSERRAT_10
#else
#define LV_FONT_MONTSERRAT_10 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_12
#ifdef CONFIG_LV_FONT_MONTSERRAT_12
#define LV_FONT_MONTSERRAT_12 CONFIG_LV_FONT_MONTSERRAT_12
#else
#define LV_FONT_MONTSERRAT_12 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_14
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_FONT_MONTSERRAT_14
#define LV_FONT_MONTSERRAT_14 CONFIG_LV_FONT_MONTSERRAT_14
#else
#define LV_FONT_MONTSERRAT_14 0
#endif
#else
#define LV_FONT_MONTSERRAT_14 1
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_16
#ifdef CONFIG_LV_FONT_MONTSERRAT_16
#define LV_FONT_MONTSERRAT_16 CONFIG_LV_FONT_MONTSERRAT_16
#else
#define LV_FONT_MONTSERRAT_16 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_18
#ifdef CONFIG_LV_FONT_MONTSERRAT_18
#define LV_FONT_MONTSERRAT_18 CONFIG_LV_FONT_MONTSERRAT_18
#else
#define LV_FONT_MONTSERRAT_18 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_20
#ifdef CONFIG_LV_FONT_MONTSERRAT_20
#define LV_FONT_MONTSERRAT_20 CONFIG_LV_FONT_MONTSERRAT_20
#else
#define LV_FONT_MONTSERRAT_20 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_22
#ifdef CONFIG_LV_FONT_MONTSERRAT_22
#define LV_FONT_MONTSERRAT_22 CONFIG_LV_FONT_MONTSERRAT_22
#else
#define LV_FONT_MONTSERRAT_22 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_24
#ifdef CONFIG_LV_FONT_MONTSERRAT_24
#define LV_FONT_MONTSERRAT_24 CONFIG_LV_FONT_MONTSERRAT_24
#else
#define LV_FONT_MONTSERRAT_24 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_26
#ifdef CONFIG_LV_FONT_MONTSERRAT_26
#define LV_FONT_MONTSERRAT_26 CONFIG_LV_FONT_MONTSERRAT_26
#else
#define LV_FONT_MONTSERRAT_26 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_28
#ifdef CONFIG_LV_FONT_MONTSERRAT_28
#define LV_FONT_MONTSERRAT_28 CONFIG_LV_FONT_MONTSERRAT_28
#else
#define LV_FONT_MONTSERRAT_28 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_30
#ifdef CONFIG_LV_FONT_MONTSERRAT_30
#define LV_FONT_MONTSERRAT_30 CONFIG_LV_FONT_MONTSERRAT_30
#else
#define LV_FONT_MONTSERRAT_30 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_32
#ifdef CONFIG_LV_FONT_MONTSERRAT_32
#define LV_FONT_MONTSERRAT_32 CONFIG_LV_FONT_MONTSERRAT_32
#else
#define LV_FONT_MONTSERRAT_32 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_34
#ifdef CONFIG_LV_FONT_MONTSERRAT_34
#define LV_FONT_MONTSERRAT_34 CONFIG_LV_FONT_MONTSERRAT_34
#else
#define LV_FONT_MONTSERRAT_34 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_36
#ifdef CONFIG_LV_FONT_MONTSERRAT_36
#define LV_FONT_MONTSERRAT_36 CONFIG_LV_FONT_MONTSERRAT_36
#else
#define LV_FONT_MONTSERRAT_36 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_38
#ifdef CONFIG_LV_FONT_MONTSERRAT_38
#define LV_FONT_MONTSERRAT_38 CONFIG_LV_FONT_MONTSERRAT_38
#else
#define LV_FONT_MONTSERRAT_38 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_40
#ifdef CONFIG_LV_FONT_MONTSERRAT_40
#define LV_FONT_MONTSERRAT_40 CONFIG_LV_FONT_MONTSERRAT_40
#else
#define LV_FONT_MONTSERRAT_40 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_42
#ifdef CONFIG_LV_FONT_MONTSERRAT_42
#define LV_FONT_MONTSERRAT_42 CONFIG_LV_FONT_MONTSERRAT_42
#else
#define LV_FONT_MONTSERRAT_42 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_44
#ifdef CONFIG_LV_FONT_MONTSERRAT_44
#define LV_FONT_MONTSERRAT_44 CONFIG_LV_FONT_MONTSERRAT_44
#else
#define LV_FONT_MONTSERRAT_44 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_46
#ifdef CONFIG_LV_FONT_MONTSERRAT_46
#define LV_FONT_MONTSERRAT_46 CONFIG_LV_FONT_MONTSERRAT_46
#else
#define LV_FONT_MONTSERRAT_46 0
#endif
#endif
#ifndef LV_FONT_MONTSERRAT_48
#ifdef CONFIG_LV_FONT_MONTSERRAT_48
#define LV_FONT_MONTSERRAT_48 CONFIG_LV_FONT_MONTSERRAT_48
#else
#define LV_FONT_MONTSERRAT_48 0
#endif
#endif
/*Demonstrate special features*/
#ifndef LV_FONT_MONTSERRAT_28_COMPRESSED
#ifdef CONFIG_LV_FONT_MONTSERRAT_28_COMPRESSED
#define LV_FONT_MONTSERRAT_28_COMPRESSED CONFIG_LV_FONT_MONTSERRAT_28_COMPRESSED
#else
#define LV_FONT_MONTSERRAT_28_COMPRESSED 0 /*bpp = 3*/
#endif
#endif
#ifndef LV_FONT_DEJAVU_16_PERSIAN_HEBREW
#ifdef CONFIG_LV_FONT_DEJAVU_16_PERSIAN_HEBREW
#define LV_FONT_DEJAVU_16_PERSIAN_HEBREW CONFIG_LV_FONT_DEJAVU_16_PERSIAN_HEBREW
#else
#define LV_FONT_DEJAVU_16_PERSIAN_HEBREW 0 /*Hebrew, Arabic, Persian letters and all their forms*/
#endif
#endif
#ifndef LV_FONT_SIMSUN_16_CJK
#ifdef CONFIG_LV_FONT_SIMSUN_16_CJK
#define LV_FONT_SIMSUN_16_CJK CONFIG_LV_FONT_SIMSUN_16_CJK
#else
#define LV_FONT_SIMSUN_16_CJK 0 /*1000 most common CJK radicals*/
#endif
#endif
/*Pixel perfect monospace fonts*/
#ifndef LV_FONT_UNSCII_8
#ifdef CONFIG_LV_FONT_UNSCII_8
#define LV_FONT_UNSCII_8 CONFIG_LV_FONT_UNSCII_8
#else
#define LV_FONT_UNSCII_8 0
#endif
#endif
#ifndef LV_FONT_UNSCII_16
#ifdef CONFIG_LV_FONT_UNSCII_16
#define LV_FONT_UNSCII_16 CONFIG_LV_FONT_UNSCII_16
#else
#define LV_FONT_UNSCII_16 0
#endif
#endif
/*Optionally declare custom fonts here.
*You can use these fonts as default font too and they will be available globally.
*E.g. #define LV_FONT_CUSTOM_DECLARE LV_FONT_DECLARE(my_font_1) LV_FONT_DECLARE(my_font_2)*/
#ifndef LV_FONT_CUSTOM_DECLARE
#ifdef CONFIG_LV_FONT_CUSTOM_DECLARE
#define LV_FONT_CUSTOM_DECLARE CONFIG_LV_FONT_CUSTOM_DECLARE
#else
#define LV_FONT_CUSTOM_DECLARE
#endif
#endif
/*Always set a default font*/
#ifndef LV_FONT_DEFAULT
#ifdef CONFIG_LV_FONT_DEFAULT
#define LV_FONT_DEFAULT CONFIG_LV_FONT_DEFAULT
#else
#define LV_FONT_DEFAULT &lv_font_montserrat_14
#endif
#endif
/*Enable handling large font and/or fonts with a lot of characters.
*The limit depends on the font size, font face and bpp.
*Compiler error will be triggered if a font needs it.*/
#ifndef LV_FONT_FMT_TXT_LARGE
#ifdef CONFIG_LV_FONT_FMT_TXT_LARGE
#define LV_FONT_FMT_TXT_LARGE CONFIG_LV_FONT_FMT_TXT_LARGE
#else
#define LV_FONT_FMT_TXT_LARGE 0
#endif
#endif
/*Enables/disables support for compressed fonts.*/
#ifndef LV_USE_FONT_COMPRESSED
#ifdef CONFIG_LV_USE_FONT_COMPRESSED
#define LV_USE_FONT_COMPRESSED CONFIG_LV_USE_FONT_COMPRESSED
#else
#define LV_USE_FONT_COMPRESSED 0
#endif
#endif
/*Enable drawing placeholders when glyph dsc is not found*/
#ifndef LV_USE_FONT_PLACEHOLDER
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_FONT_PLACEHOLDER
#define LV_USE_FONT_PLACEHOLDER CONFIG_LV_USE_FONT_PLACEHOLDER
#else
#define LV_USE_FONT_PLACEHOLDER 0
#endif
#else
#define LV_USE_FONT_PLACEHOLDER 1
#endif
#endif
/*=================
* TEXT SETTINGS
*=================*/
/**
* Select a character encoding for strings.
* Your IDE or editor should have the same character encoding
* - LV_TXT_ENC_UTF8
* - LV_TXT_ENC_ASCII
*/
#ifndef LV_TXT_ENC
#ifdef CONFIG_LV_TXT_ENC
#define LV_TXT_ENC CONFIG_LV_TXT_ENC
#else
#define LV_TXT_ENC LV_TXT_ENC_UTF8
#endif
#endif
/*Can break (wrap) texts on these chars*/
#ifndef LV_TXT_BREAK_CHARS
#ifdef CONFIG_LV_TXT_BREAK_CHARS
#define LV_TXT_BREAK_CHARS CONFIG_LV_TXT_BREAK_CHARS
#else
#define LV_TXT_BREAK_CHARS " ,.;:-_)]}"
#endif
#endif
/*If a word is at least this long, will break wherever "prettiest"
*To disable, set to a value <= 0*/
#ifndef LV_TXT_LINE_BREAK_LONG_LEN
#ifdef CONFIG_LV_TXT_LINE_BREAK_LONG_LEN
#define LV_TXT_LINE_BREAK_LONG_LEN CONFIG_LV_TXT_LINE_BREAK_LONG_LEN
#else
#define LV_TXT_LINE_BREAK_LONG_LEN 0
#endif
#endif
/*Minimum number of characters in a long word to put on a line before a break.
*Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/
#ifndef LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN
#ifdef CONFIG_LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN
#define LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN CONFIG_LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN
#else
#define LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN 3
#endif
#endif
/*Minimum number of characters in a long word to put on a line after a break.
*Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/
#ifndef LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN
#ifdef CONFIG_LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN
#define LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN CONFIG_LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN
#else
#define LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN 3
#endif
#endif
/*Support bidirectional texts. Allows mixing Left-to-Right and Right-to-Left texts.
*The direction will be processed according to the Unicode Bidirectional Algorithm:
*https://www.w3.org/International/articles/inline-bidi-markup/uba-basics*/
#ifndef LV_USE_BIDI
#ifdef CONFIG_LV_USE_BIDI
#define LV_USE_BIDI CONFIG_LV_USE_BIDI
#else
#define LV_USE_BIDI 0
#endif
#endif
#if LV_USE_BIDI
/*Set the default direction. Supported values:
*`LV_BASE_DIR_LTR` Left-to-Right
*`LV_BASE_DIR_RTL` Right-to-Left
*`LV_BASE_DIR_AUTO` detect texts base direction*/
#ifndef LV_BIDI_BASE_DIR_DEF
#ifdef CONFIG_LV_BIDI_BASE_DIR_DEF
#define LV_BIDI_BASE_DIR_DEF CONFIG_LV_BIDI_BASE_DIR_DEF
#else
#define LV_BIDI_BASE_DIR_DEF LV_BASE_DIR_AUTO
#endif
#endif
#endif
/*Enable Arabic/Persian processing
*In these languages characters should be replaced with an other form based on their position in the text*/
#ifndef LV_USE_ARABIC_PERSIAN_CHARS
#ifdef CONFIG_LV_USE_ARABIC_PERSIAN_CHARS
#define LV_USE_ARABIC_PERSIAN_CHARS CONFIG_LV_USE_ARABIC_PERSIAN_CHARS
#else
#define LV_USE_ARABIC_PERSIAN_CHARS 0
#endif
#endif
/*==================
* WIDGETS
*================*/
/*Documentation of the widgets: https://docs.lvgl.io/latest/en/html/widgets/index.html*/
#ifndef LV_WIDGETS_HAS_DEFAULT_VALUE
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_WIDGETS_HAS_DEFAULT_VALUE
#define LV_WIDGETS_HAS_DEFAULT_VALUE CONFIG_LV_WIDGETS_HAS_DEFAULT_VALUE
#else
#define LV_WIDGETS_HAS_DEFAULT_VALUE 0
#endif
#else
#define LV_WIDGETS_HAS_DEFAULT_VALUE 1
#endif
#endif
#ifndef LV_USE_ANIMIMG
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_ANIMIMG
#define LV_USE_ANIMIMG CONFIG_LV_USE_ANIMIMG
#else
#define LV_USE_ANIMIMG 0
#endif
#else
#define LV_USE_ANIMIMG 1
#endif
#endif
#ifndef LV_USE_ARC
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_ARC
#define LV_USE_ARC CONFIG_LV_USE_ARC
#else
#define LV_USE_ARC 0
#endif
#else
#define LV_USE_ARC 1
#endif
#endif
#ifndef LV_USE_BAR
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_BAR
#define LV_USE_BAR CONFIG_LV_USE_BAR
#else
#define LV_USE_BAR 0
#endif
#else
#define LV_USE_BAR 1
#endif
#endif
#ifndef LV_USE_BTN
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_BTN
#define LV_USE_BTN CONFIG_LV_USE_BTN
#else
#define LV_USE_BTN 0
#endif
#else
#define LV_USE_BTN 1
#endif
#endif
#ifndef LV_USE_BTNMATRIX
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_BTNMATRIX
#define LV_USE_BTNMATRIX CONFIG_LV_USE_BTNMATRIX
#else
#define LV_USE_BTNMATRIX 0
#endif
#else
#define LV_USE_BTNMATRIX 1
#endif
#endif
#ifndef LV_USE_CALENDAR
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_CALENDAR
#define LV_USE_CALENDAR CONFIG_LV_USE_CALENDAR
#else
#define LV_USE_CALENDAR 0
#endif
#else
#define LV_USE_CALENDAR 1
#endif
#endif
#if LV_USE_CALENDAR
#ifndef LV_CALENDAR_WEEK_STARTS_MONDAY
#ifdef CONFIG_LV_CALENDAR_WEEK_STARTS_MONDAY
#define LV_CALENDAR_WEEK_STARTS_MONDAY CONFIG_LV_CALENDAR_WEEK_STARTS_MONDAY
#else
#define LV_CALENDAR_WEEK_STARTS_MONDAY 0
#endif
#endif
#if LV_CALENDAR_WEEK_STARTS_MONDAY
#ifndef LV_CALENDAR_DEFAULT_DAY_NAMES
#ifdef CONFIG_LV_CALENDAR_DEFAULT_DAY_NAMES
#define LV_CALENDAR_DEFAULT_DAY_NAMES CONFIG_LV_CALENDAR_DEFAULT_DAY_NAMES
#else
#define LV_CALENDAR_DEFAULT_DAY_NAMES {"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"}
#endif
#endif
#else
#ifndef LV_CALENDAR_DEFAULT_DAY_NAMES
#ifdef CONFIG_LV_CALENDAR_DEFAULT_DAY_NAMES
#define LV_CALENDAR_DEFAULT_DAY_NAMES CONFIG_LV_CALENDAR_DEFAULT_DAY_NAMES
#else
#define LV_CALENDAR_DEFAULT_DAY_NAMES {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"}
#endif
#endif
#endif
#ifndef LV_CALENDAR_DEFAULT_MONTH_NAMES
#ifdef CONFIG_LV_CALENDAR_DEFAULT_MONTH_NAMES
#define LV_CALENDAR_DEFAULT_MONTH_NAMES CONFIG_LV_CALENDAR_DEFAULT_MONTH_NAMES
#else
#define LV_CALENDAR_DEFAULT_MONTH_NAMES {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
#endif
#endif
#ifndef LV_USE_CALENDAR_HEADER_ARROW
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_CALENDAR_HEADER_ARROW
#define LV_USE_CALENDAR_HEADER_ARROW CONFIG_LV_USE_CALENDAR_HEADER_ARROW
#else
#define LV_USE_CALENDAR_HEADER_ARROW 0
#endif
#else
#define LV_USE_CALENDAR_HEADER_ARROW 1
#endif
#endif
#ifndef LV_USE_CALENDAR_HEADER_DROPDOWN
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_CALENDAR_HEADER_DROPDOWN
#define LV_USE_CALENDAR_HEADER_DROPDOWN CONFIG_LV_USE_CALENDAR_HEADER_DROPDOWN
#else
#define LV_USE_CALENDAR_HEADER_DROPDOWN 0
#endif
#else
#define LV_USE_CALENDAR_HEADER_DROPDOWN 1
#endif
#endif
#endif /*LV_USE_CALENDAR*/
#ifndef LV_USE_CANVAS
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_CANVAS
#define LV_USE_CANVAS CONFIG_LV_USE_CANVAS
#else
#define LV_USE_CANVAS 0
#endif
#else
#define LV_USE_CANVAS 1
#endif
#endif
#ifndef LV_USE_CHART
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_CHART
#define LV_USE_CHART CONFIG_LV_USE_CHART
#else
#define LV_USE_CHART 0
#endif
#else
#define LV_USE_CHART 1
#endif
#endif
#ifndef LV_USE_CHECKBOX
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_CHECKBOX
#define LV_USE_CHECKBOX CONFIG_LV_USE_CHECKBOX
#else
#define LV_USE_CHECKBOX 0
#endif
#else
#define LV_USE_CHECKBOX 1
#endif
#endif
#ifndef LV_USE_DROPDOWN
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_DROPDOWN
#define LV_USE_DROPDOWN CONFIG_LV_USE_DROPDOWN
#else
#define LV_USE_DROPDOWN 0
#endif
#else
#define LV_USE_DROPDOWN 1 /*Requires: lv_label*/
#endif
#endif
#ifndef LV_USE_IMG
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_IMG
#define LV_USE_IMG CONFIG_LV_USE_IMG
#else
#define LV_USE_IMG 0
#endif
#else
#define LV_USE_IMG 1 /*Requires: lv_label*/
#endif
#endif
#ifndef LV_USE_IMGBTN
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_IMGBTN
#define LV_USE_IMGBTN CONFIG_LV_USE_IMGBTN
#else
#define LV_USE_IMGBTN 0
#endif
#else
#define LV_USE_IMGBTN 1
#endif
#endif
#ifndef LV_USE_KEYBOARD
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_KEYBOARD
#define LV_USE_KEYBOARD CONFIG_LV_USE_KEYBOARD
#else
#define LV_USE_KEYBOARD 0
#endif
#else
#define LV_USE_KEYBOARD 1
#endif
#endif
#ifndef LV_USE_LABEL
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_LABEL
#define LV_USE_LABEL CONFIG_LV_USE_LABEL
#else
#define LV_USE_LABEL 0
#endif
#else
#define LV_USE_LABEL 1
#endif
#endif
#if LV_USE_LABEL
#ifndef LV_LABEL_TEXT_SELECTION
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_LABEL_TEXT_SELECTION
#define LV_LABEL_TEXT_SELECTION CONFIG_LV_LABEL_TEXT_SELECTION
#else
#define LV_LABEL_TEXT_SELECTION 0
#endif
#else
#define LV_LABEL_TEXT_SELECTION 1 /*Enable selecting text of the label*/
#endif
#endif
#ifndef LV_LABEL_LONG_TXT_HINT
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_LABEL_LONG_TXT_HINT
#define LV_LABEL_LONG_TXT_HINT CONFIG_LV_LABEL_LONG_TXT_HINT
#else
#define LV_LABEL_LONG_TXT_HINT 0
#endif
#else
#define LV_LABEL_LONG_TXT_HINT 1 /*Store some extra info in labels to speed up drawing of very long texts*/
#endif
#endif
#endif
#ifndef LV_USE_LED
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_LED
#define LV_USE_LED CONFIG_LV_USE_LED
#else
#define LV_USE_LED 0
#endif
#else
#define LV_USE_LED 1
#endif
#endif
#ifndef LV_USE_LINE
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_LINE
#define LV_USE_LINE CONFIG_LV_USE_LINE
#else
#define LV_USE_LINE 0
#endif
#else
#define LV_USE_LINE 1
#endif
#endif
#ifndef LV_USE_LIST
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_LIST
#define LV_USE_LIST CONFIG_LV_USE_LIST
#else
#define LV_USE_LIST 0
#endif
#else
#define LV_USE_LIST 1
#endif
#endif
#ifndef LV_USE_MENU
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_MENU
#define LV_USE_MENU CONFIG_LV_USE_MENU
#else
#define LV_USE_MENU 0
#endif
#else
#define LV_USE_MENU 1
#endif
#endif
#ifndef LV_USE_METER
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_METER
#define LV_USE_METER CONFIG_LV_USE_METER
#else
#define LV_USE_METER 0
#endif
#else
#define LV_USE_METER 1
#endif
#endif
#ifndef LV_USE_MSGBOX
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_MSGBOX
#define LV_USE_MSGBOX CONFIG_LV_USE_MSGBOX
#else
#define LV_USE_MSGBOX 0
#endif
#else
#define LV_USE_MSGBOX 1
#endif
#endif
#ifndef LV_USE_ROLLER
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_ROLLER
#define LV_USE_ROLLER CONFIG_LV_USE_ROLLER
#else
#define LV_USE_ROLLER 0
#endif
#else
#define LV_USE_ROLLER 1 /*Requires: lv_label*/
#endif
#endif
#ifndef LV_USE_SCALE
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_SCALE
#define LV_USE_SCALE CONFIG_LV_USE_SCALE
#else
#define LV_USE_SCALE 0
#endif
#else
#define LV_USE_SCALE 1
#endif
#endif
#ifndef LV_USE_SLIDER
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_SLIDER
#define LV_USE_SLIDER CONFIG_LV_USE_SLIDER
#else
#define LV_USE_SLIDER 0
#endif
#else
#define LV_USE_SLIDER 1 /*Requires: lv_bar*/
#endif
#endif
#ifndef LV_USE_SPAN
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_SPAN
#define LV_USE_SPAN CONFIG_LV_USE_SPAN
#else
#define LV_USE_SPAN 0
#endif
#else
#define LV_USE_SPAN 1
#endif
#endif
#if LV_USE_SPAN
/*A line text can contain maximum num of span descriptor */
#ifndef LV_SPAN_SNIPPET_STACK_SIZE
#ifdef CONFIG_LV_SPAN_SNIPPET_STACK_SIZE
#define LV_SPAN_SNIPPET_STACK_SIZE CONFIG_LV_SPAN_SNIPPET_STACK_SIZE
#else
#define LV_SPAN_SNIPPET_STACK_SIZE 64
#endif
#endif
#endif
#ifndef LV_USE_SPINBOX
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_SPINBOX
#define LV_USE_SPINBOX CONFIG_LV_USE_SPINBOX
#else
#define LV_USE_SPINBOX 0
#endif
#else
#define LV_USE_SPINBOX 1
#endif
#endif
#ifndef LV_USE_SPINNER
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_SPINNER
#define LV_USE_SPINNER CONFIG_LV_USE_SPINNER
#else
#define LV_USE_SPINNER 0
#endif
#else
#define LV_USE_SPINNER 1
#endif
#endif
#ifndef LV_USE_SWITCH
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_SWITCH
#define LV_USE_SWITCH CONFIG_LV_USE_SWITCH
#else
#define LV_USE_SWITCH 0
#endif
#else
#define LV_USE_SWITCH 1
#endif
#endif
#ifndef LV_USE_TEXTAREA
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_TEXTAREA
#define LV_USE_TEXTAREA CONFIG_LV_USE_TEXTAREA
#else
#define LV_USE_TEXTAREA 0
#endif
#else
#define LV_USE_TEXTAREA 1 /*Requires: lv_label*/
#endif
#endif
#if LV_USE_TEXTAREA != 0
#ifndef LV_TEXTAREA_DEF_PWD_SHOW_TIME
#ifdef CONFIG_LV_TEXTAREA_DEF_PWD_SHOW_TIME
#define LV_TEXTAREA_DEF_PWD_SHOW_TIME CONFIG_LV_TEXTAREA_DEF_PWD_SHOW_TIME
#else
#define LV_TEXTAREA_DEF_PWD_SHOW_TIME 1500 /*ms*/
#endif
#endif
#endif
#ifndef LV_USE_TABLE
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_TABLE
#define LV_USE_TABLE CONFIG_LV_USE_TABLE
#else
#define LV_USE_TABLE 0
#endif
#else
#define LV_USE_TABLE 1
#endif
#endif
#ifndef LV_USE_TABVIEW
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_TABVIEW
#define LV_USE_TABVIEW CONFIG_LV_USE_TABVIEW
#else
#define LV_USE_TABVIEW 0
#endif
#else
#define LV_USE_TABVIEW 1
#endif
#endif
#ifndef LV_USE_TILEVIEW
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_TILEVIEW
#define LV_USE_TILEVIEW CONFIG_LV_USE_TILEVIEW
#else
#define LV_USE_TILEVIEW 0
#endif
#else
#define LV_USE_TILEVIEW 1
#endif
#endif
#ifndef LV_USE_WIN
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_WIN
#define LV_USE_WIN CONFIG_LV_USE_WIN
#else
#define LV_USE_WIN 0
#endif
#else
#define LV_USE_WIN 1
#endif
#endif
/*==================
* THEMES
*==================*/
/*A simple, impressive and very complete theme*/
#ifndef LV_USE_THEME_DEFAULT
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_THEME_DEFAULT
#define LV_USE_THEME_DEFAULT CONFIG_LV_USE_THEME_DEFAULT
#else
#define LV_USE_THEME_DEFAULT 0
#endif
#else
#define LV_USE_THEME_DEFAULT 1
#endif
#endif
#if LV_USE_THEME_DEFAULT
/*0: Light mode; 1: Dark mode*/
#ifndef LV_THEME_DEFAULT_DARK
#ifdef CONFIG_LV_THEME_DEFAULT_DARK
#define LV_THEME_DEFAULT_DARK CONFIG_LV_THEME_DEFAULT_DARK
#else
#define LV_THEME_DEFAULT_DARK 0
#endif
#endif
/*1: Enable grow on press*/
#ifndef LV_THEME_DEFAULT_GROW
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_THEME_DEFAULT_GROW
#define LV_THEME_DEFAULT_GROW CONFIG_LV_THEME_DEFAULT_GROW
#else
#define LV_THEME_DEFAULT_GROW 0
#endif
#else
#define LV_THEME_DEFAULT_GROW 1
#endif
#endif
/*Default transition time in [ms]*/
#ifndef LV_THEME_DEFAULT_TRANSITION_TIME
#ifdef CONFIG_LV_THEME_DEFAULT_TRANSITION_TIME
#define LV_THEME_DEFAULT_TRANSITION_TIME CONFIG_LV_THEME_DEFAULT_TRANSITION_TIME
#else
#define LV_THEME_DEFAULT_TRANSITION_TIME 80
#endif
#endif
#endif /*LV_USE_THEME_DEFAULT*/
/*A very simple theme that is a good starting point for a custom theme*/
#ifndef LV_USE_THEME_BASIC
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_THEME_BASIC
#define LV_USE_THEME_BASIC CONFIG_LV_USE_THEME_BASIC
#else
#define LV_USE_THEME_BASIC 0
#endif
#else
#define LV_USE_THEME_BASIC 1
#endif
#endif
/*A theme designed for monochrome displays*/
#ifndef LV_USE_THEME_MONO
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_THEME_MONO
#define LV_USE_THEME_MONO CONFIG_LV_USE_THEME_MONO
#else
#define LV_USE_THEME_MONO 0
#endif
#else
#define LV_USE_THEME_MONO 1
#endif
#endif
/*==================
* LAYOUTS
*==================*/
/*A layout similar to Flexbox in CSS.*/
#ifndef LV_USE_FLEX
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_FLEX
#define LV_USE_FLEX CONFIG_LV_USE_FLEX
#else
#define LV_USE_FLEX 0
#endif
#else
#define LV_USE_FLEX 1
#endif
#endif
/*A layout similar to Grid in CSS.*/
#ifndef LV_USE_GRID
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_GRID
#define LV_USE_GRID CONFIG_LV_USE_GRID
#else
#define LV_USE_GRID 0
#endif
#else
#define LV_USE_GRID 1
#endif
#endif
/*====================
* 3RD PARTS LIBRARIES
*====================*/
/*File system interfaces for common APIs */
/*API for fopen, fread, etc*/
#ifndef LV_USE_FS_STDIO
#ifdef CONFIG_LV_USE_FS_STDIO
#define LV_USE_FS_STDIO CONFIG_LV_USE_FS_STDIO
#else
#define LV_USE_FS_STDIO 0
#endif
#endif
#if LV_USE_FS_STDIO
#ifndef LV_FS_STDIO_LETTER
#ifdef CONFIG_LV_FS_STDIO_LETTER
#define LV_FS_STDIO_LETTER CONFIG_LV_FS_STDIO_LETTER
#else
#define LV_FS_STDIO_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#endif
#endif
#ifndef LV_FS_STDIO_PATH
#ifdef CONFIG_LV_FS_STDIO_PATH
#define LV_FS_STDIO_PATH CONFIG_LV_FS_STDIO_PATH
#else
#define LV_FS_STDIO_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
#endif
#endif
#ifndef LV_FS_STDIO_CACHE_SIZE
#ifdef CONFIG_LV_FS_STDIO_CACHE_SIZE
#define LV_FS_STDIO_CACHE_SIZE CONFIG_LV_FS_STDIO_CACHE_SIZE
#else
#define LV_FS_STDIO_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
#endif
#endif
/*API for open, read, etc*/
#ifndef LV_USE_FS_POSIX
#ifdef CONFIG_LV_USE_FS_POSIX
#define LV_USE_FS_POSIX CONFIG_LV_USE_FS_POSIX
#else
#define LV_USE_FS_POSIX 0
#endif
#endif
#if LV_USE_FS_POSIX
#ifndef LV_FS_POSIX_LETTER
#ifdef CONFIG_LV_FS_POSIX_LETTER
#define LV_FS_POSIX_LETTER CONFIG_LV_FS_POSIX_LETTER
#else
#define LV_FS_POSIX_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#endif
#endif
#ifndef LV_FS_POSIX_PATH
#ifdef CONFIG_LV_FS_POSIX_PATH
#define LV_FS_POSIX_PATH CONFIG_LV_FS_POSIX_PATH
#else
#define LV_FS_POSIX_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
#endif
#endif
#ifndef LV_FS_POSIX_CACHE_SIZE
#ifdef CONFIG_LV_FS_POSIX_CACHE_SIZE
#define LV_FS_POSIX_CACHE_SIZE CONFIG_LV_FS_POSIX_CACHE_SIZE
#else
#define LV_FS_POSIX_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
#endif
#endif
/*API for CreateFile, ReadFile, etc*/
#ifndef LV_USE_FS_WIN32
#ifdef CONFIG_LV_USE_FS_WIN32
#define LV_USE_FS_WIN32 CONFIG_LV_USE_FS_WIN32
#else
#define LV_USE_FS_WIN32 0
#endif
#endif
#if LV_USE_FS_WIN32
#ifndef LV_FS_WIN32_LETTER
#ifdef CONFIG_LV_FS_WIN32_LETTER
#define LV_FS_WIN32_LETTER CONFIG_LV_FS_WIN32_LETTER
#else
#define LV_FS_WIN32_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#endif
#endif
#ifndef LV_FS_WIN32_PATH
#ifdef CONFIG_LV_FS_WIN32_PATH
#define LV_FS_WIN32_PATH CONFIG_LV_FS_WIN32_PATH
#else
#define LV_FS_WIN32_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
#endif
#endif
#ifndef LV_FS_WIN32_CACHE_SIZE
#ifdef CONFIG_LV_FS_WIN32_CACHE_SIZE
#define LV_FS_WIN32_CACHE_SIZE CONFIG_LV_FS_WIN32_CACHE_SIZE
#else
#define LV_FS_WIN32_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
#endif
#endif
/*API for FATFS (needs to be added separately). Uses f_open, f_read, etc*/
#ifndef LV_USE_FS_FATFS
#ifdef CONFIG_LV_USE_FS_FATFS
#define LV_USE_FS_FATFS CONFIG_LV_USE_FS_FATFS
#else
#define LV_USE_FS_FATFS 0
#endif
#endif
#if LV_USE_FS_FATFS
#ifndef LV_FS_FATFS_LETTER
#ifdef CONFIG_LV_FS_FATFS_LETTER
#define LV_FS_FATFS_LETTER CONFIG_LV_FS_FATFS_LETTER
#else
#define LV_FS_FATFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#endif
#endif
#ifndef LV_FS_FATFS_CACHE_SIZE
#ifdef CONFIG_LV_FS_FATFS_CACHE_SIZE
#define LV_FS_FATFS_CACHE_SIZE CONFIG_LV_FS_FATFS_CACHE_SIZE
#else
#define LV_FS_FATFS_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
#endif
#endif
/*API for memory-mapped file access. */
#ifndef LV_USE_FS_MEMFS
#ifdef CONFIG_LV_USE_FS_MEMFS
#define LV_USE_FS_MEMFS CONFIG_LV_USE_FS_MEMFS
#else
#define LV_USE_FS_MEMFS 0
#endif
#endif
#if LV_USE_FS_MEMFS
#ifndef LV_FS_MEMFS_LETTER
#ifdef CONFIG_LV_FS_MEMFS_LETTER
#define LV_FS_MEMFS_LETTER CONFIG_LV_FS_MEMFS_LETTER
#else
#define LV_FS_MEMFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#endif
#endif
#endif
/*LODEPNG decoder library*/
#ifndef LV_USE_LODEPNG
#ifdef CONFIG_LV_USE_LODEPNG
#define LV_USE_LODEPNG CONFIG_LV_USE_LODEPNG
#else
#define LV_USE_LODEPNG 0
#endif
#endif
/*PNG decoder(libpng) library*/
#ifndef LV_USE_LIBPNG
#ifdef CONFIG_LV_USE_LIBPNG
#define LV_USE_LIBPNG CONFIG_LV_USE_LIBPNG
#else
#define LV_USE_LIBPNG 0
#endif
#endif
/*BMP decoder library*/
#ifndef LV_USE_BMP
#ifdef CONFIG_LV_USE_BMP
#define LV_USE_BMP CONFIG_LV_USE_BMP
#else
#define LV_USE_BMP 0
#endif
#endif
/* JPG + split JPG decoder library.
* Split JPG is a custom format optimized for embedded systems. */
#ifndef LV_USE_TJPGD
#ifdef CONFIG_LV_USE_TJPGD
#define LV_USE_TJPGD CONFIG_LV_USE_TJPGD
#else
#define LV_USE_TJPGD 0
#endif
#endif
/* libjpeg-turbo decoder library.
* Supports complete JPEG specifications and high-performance JPEG decoding. */
#ifndef LV_USE_LIBJPEG_TURBO
#ifdef CONFIG_LV_USE_LIBJPEG_TURBO
#define LV_USE_LIBJPEG_TURBO CONFIG_LV_USE_LIBJPEG_TURBO
#else
#define LV_USE_LIBJPEG_TURBO 0
#endif
#endif
/*GIF decoder library*/
#ifndef LV_USE_GIF
#ifdef CONFIG_LV_USE_GIF
#define LV_USE_GIF CONFIG_LV_USE_GIF
#else
#define LV_USE_GIF 0
#endif
#endif
/*Decode bin images to RAM*/
#ifndef LV_BIN_DECODER_RAM_LOAD
#ifdef CONFIG_LV_BIN_DECODER_RAM_LOAD
#define LV_BIN_DECODER_RAM_LOAD CONFIG_LV_BIN_DECODER_RAM_LOAD
#else
#define LV_BIN_DECODER_RAM_LOAD 0
#endif
#endif
/*QR code library*/
#ifndef LV_USE_QRCODE
#ifdef CONFIG_LV_USE_QRCODE
#define LV_USE_QRCODE CONFIG_LV_USE_QRCODE
#else
#define LV_USE_QRCODE 0
#endif
#endif
/*Barcode code library*/
#ifndef LV_USE_BARCODE
#ifdef CONFIG_LV_USE_BARCODE
#define LV_USE_BARCODE CONFIG_LV_USE_BARCODE
#else
#define LV_USE_BARCODE 0
#endif
#endif
/*FreeType library*/
#ifndef LV_USE_FREETYPE
#ifdef CONFIG_LV_USE_FREETYPE
#define LV_USE_FREETYPE CONFIG_LV_USE_FREETYPE
#else
#define LV_USE_FREETYPE 0
#endif
#endif
#if LV_USE_FREETYPE
/*Memory used by FreeType to cache characters [bytes]*/
#ifndef LV_FREETYPE_CACHE_SIZE
#ifdef CONFIG_LV_FREETYPE_CACHE_SIZE
#define LV_FREETYPE_CACHE_SIZE CONFIG_LV_FREETYPE_CACHE_SIZE
#else
#define LV_FREETYPE_CACHE_SIZE (64 * 1024)
#endif
#endif
/*Let FreeType to use LVGL memory and file porting*/
#ifndef LV_FREETYPE_USE_LVGL_PORT
#ifdef CONFIG_LV_FREETYPE_USE_LVGL_PORT
#define LV_FREETYPE_USE_LVGL_PORT CONFIG_LV_FREETYPE_USE_LVGL_PORT
#else
#define LV_FREETYPE_USE_LVGL_PORT 0
#endif
#endif
/* 1: bitmap cache use the sbit cache, 0:bitmap cache use the image cache. */
/* sbit cache:it is much more memory efficient for small bitmaps(font size < 256) */
/* if font size >= 256, must be configured as image cache */
#ifndef LV_FREETYPE_SBIT_CACHE
#ifdef CONFIG_LV_FREETYPE_SBIT_CACHE
#define LV_FREETYPE_SBIT_CACHE CONFIG_LV_FREETYPE_SBIT_CACHE
#else
#define LV_FREETYPE_SBIT_CACHE 0
#endif
#endif
/* Maximum number of opened FT_Face/FT_Size objects managed by this cache instance. */
/* (0:use system defaults) */
#ifndef LV_FREETYPE_CACHE_FT_FACES
#ifdef CONFIG_LV_FREETYPE_CACHE_FT_FACES
#define LV_FREETYPE_CACHE_FT_FACES CONFIG_LV_FREETYPE_CACHE_FT_FACES
#else
#define LV_FREETYPE_CACHE_FT_FACES 4
#endif
#endif
#ifndef LV_FREETYPE_CACHE_FT_SIZES
#ifdef CONFIG_LV_FREETYPE_CACHE_FT_SIZES
#define LV_FREETYPE_CACHE_FT_SIZES CONFIG_LV_FREETYPE_CACHE_FT_SIZES
#else
#define LV_FREETYPE_CACHE_FT_SIZES 4
#endif
#endif
#endif
/* Built-in TTF decoder */
#ifndef LV_USE_TINY_TTF
#ifdef CONFIG_LV_USE_TINY_TTF
#define LV_USE_TINY_TTF CONFIG_LV_USE_TINY_TTF
#else
#define LV_USE_TINY_TTF 0
#endif
#endif
#if LV_USE_TINY_TTF
/* Enable loading TTF data from files */
#ifndef LV_TINY_TTF_FILE_SUPPORT
#ifdef CONFIG_LV_TINY_TTF_FILE_SUPPORT
#define LV_TINY_TTF_FILE_SUPPORT CONFIG_LV_TINY_TTF_FILE_SUPPORT
#else
#define LV_TINY_TTF_FILE_SUPPORT 0
#endif
#endif
#endif
/*Rlottie library*/
#ifndef LV_USE_RLOTTIE
#ifdef CONFIG_LV_USE_RLOTTIE
#define LV_USE_RLOTTIE CONFIG_LV_USE_RLOTTIE
#else
#define LV_USE_RLOTTIE 0
#endif
#endif
/*FFmpeg library for image decoding and playing videos
*Supports all major image formats so do not enable other image decoder with it*/
#ifndef LV_USE_FFMPEG
#ifdef CONFIG_LV_USE_FFMPEG
#define LV_USE_FFMPEG CONFIG_LV_USE_FFMPEG
#else
#define LV_USE_FFMPEG 0
#endif
#endif
#if LV_USE_FFMPEG
/*Dump input information to stderr*/
#ifndef LV_FFMPEG_DUMP_FORMAT
#ifdef CONFIG_LV_FFMPEG_DUMP_FORMAT
#define LV_FFMPEG_DUMP_FORMAT CONFIG_LV_FFMPEG_DUMP_FORMAT
#else
#define LV_FFMPEG_DUMP_FORMAT 0
#endif
#endif
#endif
/*==================
* OTHERS
*==================*/
/*1: Enable API to take snapshot for object*/
#ifndef LV_USE_SNAPSHOT
#ifdef CONFIG_LV_USE_SNAPSHOT
#define LV_USE_SNAPSHOT CONFIG_LV_USE_SNAPSHOT
#else
#define LV_USE_SNAPSHOT 0
#endif
#endif
/*1: Enable system monitor component*/
#ifndef LV_USE_SYSMON
#ifdef CONFIG_LV_USE_SYSMON
#define LV_USE_SYSMON CONFIG_LV_USE_SYSMON
#else
#define LV_USE_SYSMON 0
#endif
#endif
/*1: Enable the runtime performance profiler*/
#ifndef LV_USE_PROFILER
#ifdef CONFIG_LV_USE_PROFILER
#define LV_USE_PROFILER CONFIG_LV_USE_PROFILER
#else
#define LV_USE_PROFILER 0
#endif
#endif
#if LV_USE_PROFILER
/*1: Enable the built-in profiler*/
#ifndef LV_USE_PROFILER_BUILTIN
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_USE_PROFILER_BUILTIN
#define LV_USE_PROFILER_BUILTIN CONFIG_LV_USE_PROFILER_BUILTIN
#else
#define LV_USE_PROFILER_BUILTIN 0
#endif
#else
#define LV_USE_PROFILER_BUILTIN 1
#endif
#endif
#if LV_USE_PROFILER_BUILTIN
/*Default profiler trace buffer size*/
#ifndef LV_PROFILER_BUILTIN_BUF_SIZE
#ifdef CONFIG_LV_PROFILER_BUILTIN_BUF_SIZE
#define LV_PROFILER_BUILTIN_BUF_SIZE CONFIG_LV_PROFILER_BUILTIN_BUF_SIZE
#else
#define LV_PROFILER_BUILTIN_BUF_SIZE (16 * 1024) /*[bytes]*/
#endif
#endif
#endif
/*Header to include for the profiler*/
#ifndef LV_PROFILER_INCLUDE
#ifdef CONFIG_LV_PROFILER_INCLUDE
#define LV_PROFILER_INCLUDE CONFIG_LV_PROFILER_INCLUDE
#else
#define LV_PROFILER_INCLUDE "lvgl/src/misc/lv_profiler_builtin.h"
#endif
#endif
/*Profiler start point function*/
#ifndef LV_PROFILER_BEGIN
#ifdef CONFIG_LV_PROFILER_BEGIN
#define LV_PROFILER_BEGIN CONFIG_LV_PROFILER_BEGIN
#else
#define LV_PROFILER_BEGIN LV_PROFILER_BUILTIN_BEGIN
#endif
#endif
/*Profiler end point function*/
#ifndef LV_PROFILER_END
#ifdef CONFIG_LV_PROFILER_END
#define LV_PROFILER_END CONFIG_LV_PROFILER_END
#else
#define LV_PROFILER_END LV_PROFILER_BUILTIN_END
#endif
#endif
/*Profiler start point function with custom tag*/
#ifndef LV_PROFILER_BEGIN_TAG
#ifdef CONFIG_LV_PROFILER_BEGIN_TAG
#define LV_PROFILER_BEGIN_TAG CONFIG_LV_PROFILER_BEGIN_TAG
#else
#define LV_PROFILER_BEGIN_TAG LV_PROFILER_BUILTIN_BEGIN_TAG
#endif
#endif
/*Profiler end point function with custom tag*/
#ifndef LV_PROFILER_END_TAG
#ifdef CONFIG_LV_PROFILER_END_TAG
#define LV_PROFILER_END_TAG CONFIG_LV_PROFILER_END_TAG
#else
#define LV_PROFILER_END_TAG LV_PROFILER_BUILTIN_END_TAG
#endif
#endif
#endif
/*1: Enable Monkey test*/
#ifndef LV_USE_MONKEY
#ifdef CONFIG_LV_USE_MONKEY
#define LV_USE_MONKEY CONFIG_LV_USE_MONKEY
#else
#define LV_USE_MONKEY 0
#endif
#endif
/*1: Enable grid navigation*/
#ifndef LV_USE_GRIDNAV
#ifdef CONFIG_LV_USE_GRIDNAV
#define LV_USE_GRIDNAV CONFIG_LV_USE_GRIDNAV
#else
#define LV_USE_GRIDNAV 0
#endif
#endif
/*1: Enable lv_obj fragment*/
#ifndef LV_USE_FRAGMENT
#ifdef CONFIG_LV_USE_FRAGMENT
#define LV_USE_FRAGMENT CONFIG_LV_USE_FRAGMENT
#else
#define LV_USE_FRAGMENT 0
#endif
#endif
/*1: Support using images as font in label or span widgets */
#ifndef LV_USE_IMGFONT
#ifdef CONFIG_LV_USE_IMGFONT
#define LV_USE_IMGFONT CONFIG_LV_USE_IMGFONT
#else
#define LV_USE_IMGFONT 0
#endif
#endif
#if LV_USE_IMGFONT
/*Imgfont image file path maximum length*/
#ifndef LV_IMGFONT_PATH_MAX_LEN
#ifdef CONFIG_LV_IMGFONT_PATH_MAX_LEN
#define LV_IMGFONT_PATH_MAX_LEN CONFIG_LV_IMGFONT_PATH_MAX_LEN
#else
#define LV_IMGFONT_PATH_MAX_LEN 64
#endif
#endif
/*1: Use img cache to buffer header information*/
#ifndef LV_IMGFONT_USE_IMAGE_CACHE_HEADER
#ifdef CONFIG_LV_IMGFONT_USE_IMAGE_CACHE_HEADER
#define LV_IMGFONT_USE_IMAGE_CACHE_HEADER CONFIG_LV_IMGFONT_USE_IMAGE_CACHE_HEADER
#else
#define LV_IMGFONT_USE_IMAGE_CACHE_HEADER 0
#endif
#endif
#endif
/*1: Enable an observer pattern implementation*/
#ifndef LV_USE_OBSERVER
#ifdef CONFIG_LV_USE_OBSERVER
#define LV_USE_OBSERVER CONFIG_LV_USE_OBSERVER
#else
#define LV_USE_OBSERVER 0
#endif
#endif
/*1: Enable Pinyin input method*/
/*Requires: lv_keyboard*/
#ifndef LV_USE_IME_PINYIN
#ifdef CONFIG_LV_USE_IME_PINYIN
#define LV_USE_IME_PINYIN CONFIG_LV_USE_IME_PINYIN
#else
#define LV_USE_IME_PINYIN 0
#endif
#endif
#if LV_USE_IME_PINYIN
/*1: Use default thesaurus*/
/*If you do not use the default thesaurus, be sure to use `lv_ime_pinyin` after setting the thesauruss*/
#ifndef LV_IME_PINYIN_USE_DEFAULT_DICT
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_IME_PINYIN_USE_DEFAULT_DICT
#define LV_IME_PINYIN_USE_DEFAULT_DICT CONFIG_LV_IME_PINYIN_USE_DEFAULT_DICT
#else
#define LV_IME_PINYIN_USE_DEFAULT_DICT 0
#endif
#else
#define LV_IME_PINYIN_USE_DEFAULT_DICT 1
#endif
#endif
/*Set the maximum number of candidate panels that can be displayed*/
/*This needs to be adjusted according to the size of the screen*/
#ifndef LV_IME_PINYIN_CAND_TEXT_NUM
#ifdef CONFIG_LV_IME_PINYIN_CAND_TEXT_NUM
#define LV_IME_PINYIN_CAND_TEXT_NUM CONFIG_LV_IME_PINYIN_CAND_TEXT_NUM
#else
#define LV_IME_PINYIN_CAND_TEXT_NUM 6
#endif
#endif
/*Use 9 key input(k9)*/
#ifndef LV_IME_PINYIN_USE_K9_MODE
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_IME_PINYIN_USE_K9_MODE
#define LV_IME_PINYIN_USE_K9_MODE CONFIG_LV_IME_PINYIN_USE_K9_MODE
#else
#define LV_IME_PINYIN_USE_K9_MODE 0
#endif
#else
#define LV_IME_PINYIN_USE_K9_MODE 1
#endif
#endif
#if LV_IME_PINYIN_USE_K9_MODE == 1
#ifndef LV_IME_PINYIN_K9_CAND_TEXT_NUM
#ifdef CONFIG_LV_IME_PINYIN_K9_CAND_TEXT_NUM
#define LV_IME_PINYIN_K9_CAND_TEXT_NUM CONFIG_LV_IME_PINYIN_K9_CAND_TEXT_NUM
#else
#define LV_IME_PINYIN_K9_CAND_TEXT_NUM 3
#endif
#endif
#endif // LV_IME_PINYIN_USE_K9_MODE
#endif
/*1: Enable file explorer*/
/*Requires: lv_table*/
#ifndef LV_USE_FILE_EXPLORER
#ifdef CONFIG_LV_USE_FILE_EXPLORER
#define LV_USE_FILE_EXPLORER CONFIG_LV_USE_FILE_EXPLORER
#else
#define LV_USE_FILE_EXPLORER 0
#endif
#endif
#if LV_USE_FILE_EXPLORER
/*Maximum length of path*/
#ifndef LV_FILE_EXPLORER_PATH_MAX_LEN
#ifdef CONFIG_LV_FILE_EXPLORER_PATH_MAX_LEN
#define LV_FILE_EXPLORER_PATH_MAX_LEN CONFIG_LV_FILE_EXPLORER_PATH_MAX_LEN
#else
#define LV_FILE_EXPLORER_PATH_MAX_LEN (128)
#endif
#endif
/*Quick access bar, 1:use, 0:not use*/
/*Requires: lv_list*/
#ifndef LV_FILE_EXPLORER_QUICK_ACCESS
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_FILE_EXPLORER_QUICK_ACCESS
#define LV_FILE_EXPLORER_QUICK_ACCESS CONFIG_LV_FILE_EXPLORER_QUICK_ACCESS
#else
#define LV_FILE_EXPLORER_QUICK_ACCESS 0
#endif
#else
#define LV_FILE_EXPLORER_QUICK_ACCESS 1
#endif
#endif
#endif
/*==================
* DEVICES
*==================*/
/*Use SDL to open window on PC and handle mouse and keyboard*/
#ifndef LV_USE_SDL
#ifdef CONFIG_LV_USE_SDL
#define LV_USE_SDL CONFIG_LV_USE_SDL
#else
#define LV_USE_SDL 0
#endif
#endif
#if LV_USE_SDL
#ifndef LV_SDL_INCLUDE_PATH
#ifdef CONFIG_LV_SDL_INCLUDE_PATH
#define LV_SDL_INCLUDE_PATH CONFIG_LV_SDL_INCLUDE_PATH
#else
#define LV_SDL_INCLUDE_PATH <SDL2/SDL.h>
#endif
#endif
#ifndef LV_SDL_RENDER_MODE
#ifdef CONFIG_LV_SDL_RENDER_MODE
#define LV_SDL_RENDER_MODE CONFIG_LV_SDL_RENDER_MODE
#else
#define LV_SDL_RENDER_MODE LV_DISPLAY_RENDER_MODE_DIRECT /*LV_DISPLAY_RENDER_MODE_DIRECT is recommended for best performance*/
#endif
#endif
#ifndef LV_SDL_BUF_COUNT
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_SDL_BUF_COUNT
#define LV_SDL_BUF_COUNT CONFIG_LV_SDL_BUF_COUNT
#else
#define LV_SDL_BUF_COUNT 0
#endif
#else
#define LV_SDL_BUF_COUNT 1 /*1 or 2*/
#endif
#endif
#ifndef LV_SDL_FULLSCREEN
#ifdef CONFIG_LV_SDL_FULLSCREEN
#define LV_SDL_FULLSCREEN CONFIG_LV_SDL_FULLSCREEN
#else
#define LV_SDL_FULLSCREEN 0 /*1: Make the window full screen by default*/
#endif
#endif
#ifndef LV_SDL_DIRECT_EXIT
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_SDL_DIRECT_EXIT
#define LV_SDL_DIRECT_EXIT CONFIG_LV_SDL_DIRECT_EXIT
#else
#define LV_SDL_DIRECT_EXIT 0
#endif
#else
#define LV_SDL_DIRECT_EXIT 1 /*1: Exit the application when all SDL windows are closed*/
#endif
#endif
#endif
/*Driver for /dev/fb*/
#ifndef LV_USE_LINUX_FBDEV
#ifdef CONFIG_LV_USE_LINUX_FBDEV
#define LV_USE_LINUX_FBDEV CONFIG_LV_USE_LINUX_FBDEV
#else
#define LV_USE_LINUX_FBDEV 0
#endif
#endif
#if LV_USE_LINUX_FBDEV
#ifndef LV_LINUX_FBDEV_BSD
#ifdef CONFIG_LV_LINUX_FBDEV_BSD
#define LV_LINUX_FBDEV_BSD CONFIG_LV_LINUX_FBDEV_BSD
#else
#define LV_LINUX_FBDEV_BSD 0
#endif
#endif
#ifndef LV_LINUX_FBDEV_RENDER_MODE
#ifdef CONFIG_LV_LINUX_FBDEV_RENDER_MODE
#define LV_LINUX_FBDEV_RENDER_MODE CONFIG_LV_LINUX_FBDEV_RENDER_MODE
#else
#define LV_LINUX_FBDEV_RENDER_MODE LV_DISPLAY_RENDER_MODE_PARTIAL
#endif
#endif
#ifndef LV_LINUX_FBDEV_BUFFER_COUNT
#ifdef CONFIG_LV_LINUX_FBDEV_BUFFER_COUNT
#define LV_LINUX_FBDEV_BUFFER_COUNT CONFIG_LV_LINUX_FBDEV_BUFFER_COUNT
#else
#define LV_LINUX_FBDEV_BUFFER_COUNT 0
#endif
#endif
#ifndef LV_LINUX_FBDEV_BUFFER_SIZE
#ifdef CONFIG_LV_LINUX_FBDEV_BUFFER_SIZE
#define LV_LINUX_FBDEV_BUFFER_SIZE CONFIG_LV_LINUX_FBDEV_BUFFER_SIZE
#else
#define LV_LINUX_FBDEV_BUFFER_SIZE 60
#endif
#endif
#endif
/*Use Nuttx to open window and handle touchscreen*/
#ifndef LV_USE_NUTTX
#ifdef CONFIG_LV_USE_NUTTX
#define LV_USE_NUTTX CONFIG_LV_USE_NUTTX
#else
#define LV_USE_NUTTX 0
#endif
#endif
#if LV_USE_NUTTX
#ifndef LV_USE_NUTTX_LIBUV
#ifdef CONFIG_LV_USE_NUTTX_LIBUV
#define LV_USE_NUTTX_LIBUV CONFIG_LV_USE_NUTTX_LIBUV
#else
#define LV_USE_NUTTX_LIBUV 0
#endif
#endif
/*Use Nuttx custom init API to open window and handle touchscreen*/
#ifndef LV_USE_NUTTX_CUSTOM_INIT
#ifdef CONFIG_LV_USE_NUTTX_CUSTOM_INIT
#define LV_USE_NUTTX_CUSTOM_INIT CONFIG_LV_USE_NUTTX_CUSTOM_INIT
#else
#define LV_USE_NUTTX_CUSTOM_INIT 0
#endif
#endif
/*Driver for /dev/lcd*/
#ifndef LV_USE_NUTTX_LCD
#ifdef CONFIG_LV_USE_NUTTX_LCD
#define LV_USE_NUTTX_LCD CONFIG_LV_USE_NUTTX_LCD
#else
#define LV_USE_NUTTX_LCD 0
#endif
#endif
#if LV_USE_NUTTX_LCD
#ifndef LV_NUTTX_LCD_BUFFER_COUNT
#ifdef CONFIG_LV_NUTTX_LCD_BUFFER_COUNT
#define LV_NUTTX_LCD_BUFFER_COUNT CONFIG_LV_NUTTX_LCD_BUFFER_COUNT
#else
#define LV_NUTTX_LCD_BUFFER_COUNT 0
#endif
#endif
#ifndef LV_NUTTX_LCD_BUFFER_SIZE
#ifdef CONFIG_LV_NUTTX_LCD_BUFFER_SIZE
#define LV_NUTTX_LCD_BUFFER_SIZE CONFIG_LV_NUTTX_LCD_BUFFER_SIZE
#else
#define LV_NUTTX_LCD_BUFFER_SIZE 60
#endif
#endif
#endif
/*Driver for /dev/input*/
#ifndef LV_USE_NUTTX_TOUCHSCREEN
#ifdef CONFIG_LV_USE_NUTTX_TOUCHSCREEN
#define LV_USE_NUTTX_TOUCHSCREEN CONFIG_LV_USE_NUTTX_TOUCHSCREEN
#else
#define LV_USE_NUTTX_TOUCHSCREEN 0
#endif
#endif
#endif
/*Driver for /dev/dri/card*/
#ifndef LV_USE_LINUX_DRM
#ifdef CONFIG_LV_USE_LINUX_DRM
#define LV_USE_LINUX_DRM CONFIG_LV_USE_LINUX_DRM
#else
#define LV_USE_LINUX_DRM 0
#endif
#endif
/*Interface for TFT_eSPI*/
#ifndef LV_USE_TFT_ESPI
#ifdef CONFIG_LV_USE_TFT_ESPI
#define LV_USE_TFT_ESPI CONFIG_LV_USE_TFT_ESPI
#else
#define LV_USE_TFT_ESPI 0
#endif
#endif
/*Driver for evdev input devices*/
#ifndef LV_USE_EVDEV
#ifdef CONFIG_LV_USE_EVDEV
#define LV_USE_EVDEV CONFIG_LV_USE_EVDEV
#else
#define LV_USE_EVDEV 0
#endif
#endif
/*==================
* EXAMPLES
*==================*/
/*Enable the examples to be built with the library*/
#ifndef LV_BUILD_EXAMPLES
#ifdef _LV_KCONFIG_PRESENT
#ifdef CONFIG_LV_BUILD_EXAMPLES
#define LV_BUILD_EXAMPLES CONFIG_LV_BUILD_EXAMPLES
#else
#define LV_BUILD_EXAMPLES 0
#endif
#else
#define LV_BUILD_EXAMPLES 1
#endif
#endif
/*===================
* DEMO USAGE
====================*/
/*Show some widget. It might be required to increase `LV_MEM_SIZE` */
#ifndef LV_USE_DEMO_WIDGETS
#ifdef CONFIG_LV_USE_DEMO_WIDGETS
#define LV_USE_DEMO_WIDGETS CONFIG_LV_USE_DEMO_WIDGETS
#else
#define LV_USE_DEMO_WIDGETS 0
#endif
#endif
#if LV_USE_DEMO_WIDGETS
#ifndef LV_DEMO_WIDGETS_SLIDESHOW
#ifdef CONFIG_LV_DEMO_WIDGETS_SLIDESHOW
#define LV_DEMO_WIDGETS_SLIDESHOW CONFIG_LV_DEMO_WIDGETS_SLIDESHOW
#else
#define LV_DEMO_WIDGETS_SLIDESHOW 0
#endif
#endif
#endif
/*Demonstrate the usage of encoder and keyboard*/
#ifndef LV_USE_DEMO_KEYPAD_AND_ENCODER
#ifdef CONFIG_LV_USE_DEMO_KEYPAD_AND_ENCODER
#define LV_USE_DEMO_KEYPAD_AND_ENCODER CONFIG_LV_USE_DEMO_KEYPAD_AND_ENCODER
#else
#define LV_USE_DEMO_KEYPAD_AND_ENCODER 0
#endif
#endif
/*Benchmark your system*/
#ifndef LV_USE_DEMO_BENCHMARK
#ifdef CONFIG_LV_USE_DEMO_BENCHMARK
#define LV_USE_DEMO_BENCHMARK CONFIG_LV_USE_DEMO_BENCHMARK
#else
#define LV_USE_DEMO_BENCHMARK 0
#endif
#endif
/*Render test for each primitives. Requires at least 480x272 display*/
#ifndef LV_USE_DEMO_RENDER
#ifdef CONFIG_LV_USE_DEMO_RENDER
#define LV_USE_DEMO_RENDER CONFIG_LV_USE_DEMO_RENDER
#else
#define LV_USE_DEMO_RENDER 0
#endif
#endif
/*Stress test for LVGL*/
#ifndef LV_USE_DEMO_STRESS
#ifdef CONFIG_LV_USE_DEMO_STRESS
#define LV_USE_DEMO_STRESS CONFIG_LV_USE_DEMO_STRESS
#else
#define LV_USE_DEMO_STRESS 0
#endif
#endif
/*Music player demo*/
#ifndef LV_USE_DEMO_MUSIC
#ifdef CONFIG_LV_USE_DEMO_MUSIC
#define LV_USE_DEMO_MUSIC CONFIG_LV_USE_DEMO_MUSIC
#else
#define LV_USE_DEMO_MUSIC 0
#endif
#endif
#if LV_USE_DEMO_MUSIC
#ifndef LV_DEMO_MUSIC_SQUARE
#ifdef CONFIG_LV_DEMO_MUSIC_SQUARE
#define LV_DEMO_MUSIC_SQUARE CONFIG_LV_DEMO_MUSIC_SQUARE
#else
#define LV_DEMO_MUSIC_SQUARE 0
#endif
#endif
#ifndef LV_DEMO_MUSIC_LANDSCAPE
#ifdef CONFIG_LV_DEMO_MUSIC_LANDSCAPE
#define LV_DEMO_MUSIC_LANDSCAPE CONFIG_LV_DEMO_MUSIC_LANDSCAPE
#else
#define LV_DEMO_MUSIC_LANDSCAPE 0
#endif
#endif
#ifndef LV_DEMO_MUSIC_ROUND
#ifdef CONFIG_LV_DEMO_MUSIC_ROUND
#define LV_DEMO_MUSIC_ROUND CONFIG_LV_DEMO_MUSIC_ROUND
#else
#define LV_DEMO_MUSIC_ROUND 0
#endif
#endif
#ifndef LV_DEMO_MUSIC_LARGE
#ifdef CONFIG_LV_DEMO_MUSIC_LARGE
#define LV_DEMO_MUSIC_LARGE CONFIG_LV_DEMO_MUSIC_LARGE
#else
#define LV_DEMO_MUSIC_LARGE 0
#endif
#endif
#ifndef LV_DEMO_MUSIC_AUTO_PLAY
#ifdef CONFIG_LV_DEMO_MUSIC_AUTO_PLAY
#define LV_DEMO_MUSIC_AUTO_PLAY CONFIG_LV_DEMO_MUSIC_AUTO_PLAY
#else
#define LV_DEMO_MUSIC_AUTO_PLAY 0
#endif
#endif
#endif
/*Flex layout demo*/
#ifndef LV_USE_DEMO_FLEX_LAYOUT
#ifdef CONFIG_LV_USE_DEMO_FLEX_LAYOUT
#define LV_USE_DEMO_FLEX_LAYOUT CONFIG_LV_USE_DEMO_FLEX_LAYOUT
#else
#define LV_USE_DEMO_FLEX_LAYOUT 0
#endif
#endif
/*Smart-phone like multi-language demo*/
#ifndef LV_USE_DEMO_MULTILANG
#ifdef CONFIG_LV_USE_DEMO_MULTILANG
#define LV_USE_DEMO_MULTILANG CONFIG_LV_USE_DEMO_MULTILANG
#else
#define LV_USE_DEMO_MULTILANG 0
#endif
#endif
/*Widget transformation demo*/
#ifndef LV_USE_DEMO_TRANSFORM
#ifdef CONFIG_LV_USE_DEMO_TRANSFORM
#define LV_USE_DEMO_TRANSFORM CONFIG_LV_USE_DEMO_TRANSFORM
#else
#define LV_USE_DEMO_TRANSFORM 0
#endif
#endif
/*Demonstrate scroll settings*/
#ifndef LV_USE_DEMO_SCROLL
#ifdef CONFIG_LV_USE_DEMO_SCROLL
#define LV_USE_DEMO_SCROLL CONFIG_LV_USE_DEMO_SCROLL
#else
#define LV_USE_DEMO_SCROLL 0
#endif
#endif
/*----------------------------------
* End of parsing lv_conf_template.h
-----------------------------------*/
LV_EXPORT_CONST_INT(LV_DPI_DEF);
#undef _LV_KCONFIG_PRESENT
#if LV_USE_FLOAT
typedef float lv_value_precise_t;
#else
typedef int32_t lv_value_precise_t;
#endif
/*Set some defines if a dependency is disabled*/
#if LV_USE_LOG == 0
#define LV_LOG_LEVEL LV_LOG_LEVEL_NONE
#define LV_LOG_TRACE_MEM 0
#define LV_LOG_TRACE_TIMER 0
#define LV_LOG_TRACE_INDEV 0
#define LV_LOG_TRACE_DISP_REFR 0
#define LV_LOG_TRACE_EVENT 0
#define LV_LOG_TRACE_OBJ_CREATE 0
#define LV_LOG_TRACE_LAYOUT 0
#define LV_LOG_TRACE_ANIM 0
#endif /*LV_USE_LOG*/
/*If running without lv_conf.h add typedefs with default value*/
#ifdef LV_CONF_SKIP
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) /*Disable warnings for Visual Studio*/
#define _CRT_SECURE_NO_WARNINGS
#endif
#endif /*defined(LV_CONF_SKIP)*/
#endif /*LV_CONF_INTERNAL_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl | repos/zig_workbench/BaseLVGL/lib/lvgl/src/lvgl.h | /**
* @file lvgl.h
* This file exists only to be compatible with Arduino's library structure
*/
#ifndef LVGL_SRC_H
#define LVGL_SRC_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lvgl.h"
#include "lv_conf_internal.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LVGL_SRC_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl | repos/zig_workbench/BaseLVGL/lib/lvgl/src/lv_init.h | /**
* @file lv_init.h
*
*/
#ifndef LV_INIT_H
#define LV_INIT_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include <stdbool.h>
#include "lv_conf_internal.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Initialize LVGL library.
* Should be called before any other LVGL related function.
*/
void lv_init(void);
/**
* Deinit the 'lv' library
*/
void lv_deinit(void);
/**
* Returns whether the 'lv' library is currently initialized
*/
bool lv_is_initialized(void);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_INIT_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl | repos/zig_workbench/BaseLVGL/lib/lvgl/src/lv_init.c | /**
* @file lv_init.c
*
*/
/*********************
* INCLUDES
*********************/
#include "core/lv_global.h"
#include "core/lv_obj.h"
#include "display/lv_display_private.h"
#include "indev/lv_indev_private.h"
#include "layouts/lv_layout.h"
#include "libs/bmp/lv_bmp.h"
//#include "libs/ffmpeg/lv_ffmpeg.h"
//#include "libs/freetype/lv_freetype.h"
#include "libs/fsdrv/lv_fsdrv.h"
//#include "libs/gif/lv_gif.h"
#include "libs/tjpgd/lv_tjpgd.h"
#include "libs/libjpeg_turbo/lv_libjpeg_turbo.h"
#include "libs/lodepng/lv_lodepng.h"
#include "libs/libpng/lv_libpng.h"
#include "draw/lv_draw.h"
#include "misc/lv_cache.h"
#include "misc/lv_cache_builtin.h"
#include "misc/lv_async.h"
#include "misc/lv_fs.h"
#if LV_USE_DRAW_VGLITE
#include "draw/nxp/vglite/lv_draw_vglite.h"
#endif
#if LV_USE_DRAW_PXP
#include "draw/nxp/pxp/lv_draw_pxp.h"
#endif
/*********************
* DEFINES
*********************/
#define lv_initialized LV_GLOBAL_DEFAULT()->inited
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
#if LV_ENABLE_GLOBAL_CUSTOM == 0
lv_global_t lv_global;
#endif
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
static inline void lv_global_init(lv_global_t * global)
{
LV_ASSERT_NULL(global);
if(global == NULL) {
LV_LOG_ERROR("lv_global cannot be null");
return;
}
lv_memset(global, 0, sizeof(lv_global_t));
_lv_ll_init(&(global->disp_ll), sizeof(lv_display_t));
_lv_ll_init(&(global->indev_ll), sizeof(lv_indev_t));
global->memory_zero = ZERO_MEM_SENTINEL;
global->style_refresh = true;
global->layout_count = _LV_LAYOUT_LAST;
global->style_last_custom_prop_id = (uint32_t)_LV_STYLE_LAST_BUILT_IN_PROP;
global->area_trans_cache.angle_prev = INT32_MIN;
global->event_last_register_id = _LV_EVENT_LAST;
global->math_rand_seed = 0x1234ABCD;
#if defined(LV_DRAW_SW_SHADOW_CACHE_SIZE) && LV_DRAW_SW_SHADOW_CACHE_SIZE > 0
global->sw_shadow_cache.cache_size = -1;
global->sw_shadow_cache.cache_r = -1;
#endif
}
bool lv_is_initialized(void)
{
#if LV_ENABLE_GLOBAL_CUSTOM
if(LV_GLOBAL_DEFAULT()) return lv_initialized;
else return false;
#else
return lv_initialized;
#endif
}
void lv_init(void)
{
/*First initialize Garbage Collection if needed*/
#ifdef LV_GC_INIT
LV_GC_INIT();
#endif
/*Do nothing if already initialized*/
if(lv_initialized) {
LV_LOG_WARN("lv_init: already initialized");
return;
}
LV_LOG_INFO("begin");
/*Initialize members of static variable lv_global */
lv_global_init(LV_GLOBAL_DEFAULT());
lv_mem_init();
_lv_draw_buf_init_handlers();
#if LV_USE_SPAN != 0
lv_span_stack_init();
#endif
#if LV_USE_PROFILER && LV_USE_PROFILER_BUILTIN
lv_profiler_builtin_config_t profiler_config;
lv_profiler_builtin_config_init(&profiler_config);
lv_profiler_builtin_init(&profiler_config);
#endif
_lv_timer_core_init();
_lv_fs_init();
_lv_layout_init();
_lv_anim_core_init();
_lv_group_init();
lv_draw_init();
#if LV_USE_DRAW_SW
lv_draw_sw_init();
#endif
#if LV_USE_DRAW_VGLITE
lv_draw_vglite_init();
#endif
#if LV_USE_DRAW_PXP
lv_draw_pxp_init();
#endif
_lv_obj_style_init();
/*Initialize the screen refresh system*/
_lv_refr_init();
#if LV_USE_SYSMON
_lv_sysmon_builtin_init();
#endif
_lv_image_decoder_init();
_lv_cache_init();
_lv_cache_builtin_init();
lv_cache_lock();
lv_cache_set_max_size(LV_CACHE_DEF_SIZE);
lv_cache_unlock();
/*Test if the IDE has UTF-8 encoding*/
const char * txt = "Á";
uint8_t * txt_u8 = (uint8_t *)txt;
if(txt_u8[0] != 0xc3 || txt_u8[1] != 0x81 || txt_u8[2] != 0x00) {
LV_LOG_WARN("The strings have no UTF-8 encoding. Non-ASCII characters won't be displayed.");
}
uint32_t endianness_test = 0x11223344;
uint8_t * endianness_test_p = (uint8_t *) &endianness_test;
bool big_endian = endianness_test_p[0] == 0x11;
if(big_endian) {
LV_ASSERT_MSG(LV_BIG_ENDIAN_SYSTEM == 1,
"It's a big endian system but LV_BIG_ENDIAN_SYSTEM is not enabled in lv_conf.h");
}
else {
LV_ASSERT_MSG(LV_BIG_ENDIAN_SYSTEM == 0,
"It's a little endian system but LV_BIG_ENDIAN_SYSTEM is enabled in lv_conf.h");
}
#if LV_USE_ASSERT_MEM_INTEGRITY
LV_LOG_WARN("Memory integrity checks are enabled via LV_USE_ASSERT_MEM_INTEGRITY which makes LVGL much slower");
#endif
#if LV_USE_ASSERT_OBJ
LV_LOG_WARN("Object sanity checks are enabled via LV_USE_ASSERT_OBJ which makes LVGL much slower");
#endif
#if LV_USE_ASSERT_STYLE
LV_LOG_WARN("Style sanity checks are enabled that uses more RAM");
#endif
#if LV_LOG_LEVEL == LV_LOG_LEVEL_TRACE
LV_LOG_WARN("Log level is set to 'Trace' which makes LVGL much slower");
#endif
#if LV_USE_FS_FATFS != '\0'
lv_fs_fatfs_init();
#endif
#if LV_USE_FS_STDIO != '\0'
lv_fs_stdio_init();
#endif
#if LV_USE_FS_POSIX != '\0'
lv_fs_posix_init();
#endif
#if LV_USE_FS_WIN32 != '\0'
lv_fs_win32_init();
#endif
#if LV_USE_FS_MEMFS
lv_fs_memfs_init();
#endif
#if LV_USE_LODEPNG
lv_lodepng_init();
#endif
#if LV_USE_LIBPNG
lv_libpng_init();
#endif
#if LV_USE_TJPGD
lv_tjpgd_init();
#endif
#if LV_USE_LIBJPEG_TURBO
lv_libjpeg_turbo_init();
#endif
#if LV_USE_BMP
lv_bmp_init();
#endif
/*Make FFMPEG last because the last converter will be checked first and
*it's superior to any other */
#if LV_USE_FFMPEG
lv_ffmpeg_init();
#endif
#if LV_USE_FREETYPE
/*Init freetype library*/
# if LV_FREETYPE_CACHE_SIZE >= 0
lv_freetype_init(LV_FREETYPE_CACHE_FT_FACES, LV_FREETYPE_CACHE_FT_SIZES, LV_FREETYPE_CACHE_SIZE);
# else
lv_freetype_init(0, 0, 0);
# endif
#endif
lv_initialized = true;
LV_LOG_TRACE("finished");
}
void lv_deinit(void)
{
/*Do nothing if already deinit*/
if(!lv_initialized) {
LV_LOG_WARN("lv_deinit: already deinit!");
return;
}
#if LV_ENABLE_GLOBAL_CUSTOM || LV_USE_STDLIB_MALLOC == LV_STDLIB_BUILTIN
#if LV_USE_SYSMON
_lv_sysmon_builtin_deinit();
#endif
lv_display_set_default(NULL);
#if LV_USE_SPAN != 0
lv_span_stack_deinit();
#endif
#if LV_USE_FREETYPE
lv_freetype_uninit();
#endif
#if LV_USE_THEME_DEFAULT
lv_theme_default_deinit();
#endif
#if LV_USE_THEME_BASIC
lv_theme_basic_deinit();
#endif
#if LV_USE_THEME_MONO
lv_theme_mono_deinit();
#endif
lv_mem_deinit();
#if LV_USE_LOG
lv_log_register_print_cb(NULL);
#endif
#if LV_USE_OBJ_ID_BUILTIN
lv_objid_builtin_destroy();
#endif
#endif
lv_initialized = false;
LV_LOG_INFO("lv_deinit done");
}
/**********************
* STATIC FUNCTIONS
**********************/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl | repos/zig_workbench/BaseLVGL/lib/lvgl/src/lv_conf_kconfig.h | /** * @file lv_conf_kconfig.h * Configs that need special handling when LVGL is used with Kconfig */
#ifndef LV_CONF_KCONFIG_H
#define LV_CONF_KCONFIG_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef LV_CONF_KCONFIG_EXTERNAL_INCLUDE
# include LV_CONF_KCONFIG_EXTERNAL_INCLUDE
#else
# ifdef ESP_PLATFORM
# include "sdkconfig.h"
# include "esp_attr.h"
# endif
# ifdef __NuttX__
# include <nuttx/config.h>
# elif defined(__RTTHREAD__)
# define LV_CONF_INCLUDE_SIMPLE
# include <lv_rt_thread_conf.h>
# endif
#endif /*LV_CONF_KCONFIG_EXTERNAL_INCLUDE*/
/*******************
* LV_USE_STDLIB_MALLOC
*******************/
#ifdef CONFIG_LV_USE_BUILTIN_MALLOC
# define CONFIG_LV_USE_STDLIB_MALLOC LV_STDLIB_BUILTIN
#elif defined(CONFIG_LV_USE_CLIB_MALLOC)
# define CONFIG_LV_USE_STDLIB_MALLOC LV_STDLIB_CLIB
#elif defined (CONFIG_LV_USE_CUSTOM_MALLOC)
# define CONFIG_LV_USE_STDLIB_MALLOC LV_STDLIB_CUSTOM
#endif
/*******************
* LV_USE_STDLIB_STRING
*******************/
#ifdef CONFIG_LV_USE_BUILTIN_STRING
# define CONFIG_LV_USE_STDLIB_STRING LV_STDLIB_BUILTIN
#elif defined(CONFIG_LV_USE_CLIB_STRING)
# define CONFIG_LV_USE_STDLIB_STRING LV_STDLIB_CLIB
#elif defined (CONFIG_LV_USE_CUSTOM_STRING)
# define CONFIG_LV_USE_STDLIB_STRING LV_STDLIB_CUSTOM
#endif
/*******************
* LV_USE_STDLIB_SPRINTF
*******************/
#ifdef CONFIG_LV_USE_BUILTIN_SPRINTF
# define CONFIG_LV_USE_STDLIB_SPRINTF LV_STDLIB_BUILTIN
#elif defined(CONFIG_LV_USE_CLIB_SPRINTF)
# define CONFIG_LV_USE_STDLIB_SPRINTF LV_STDLIB_CLIB
#elif defined (CONFIG_LV_USE_CUSTOM_SPRINTF)
# define CONFIG_LV_USE_STDLIB_SPRINTF LV_STDLIB_CUSTOM
#endif
/*******************
* LV_MEM_SIZE
*******************/
#ifdef CONFIG_LV_MEM_SIZE_KILOBYTES
# if(CONFIG_LV_MEM_SIZE_KILOBYTES < 2)
# error "LV_MEM_SIZE >= 2kB is required"
# endif
# define CONFIG_LV_MEM_SIZE (CONFIG_LV_MEM_SIZE_KILOBYTES * 1024U)
#endif
#ifdef CONFIG_LV_MEM_POOL_EXPAND_SIZE_KILOBYTES
# define CONFIG_LV_MEM_POOL_EXPAND_SIZE (CONFIG_LV_MEM_POOL_EXPAND_SIZE_KILOBYTES * 1024U)
#endif
/*------------------
* MONITOR POSITION
*-----------------*/
#ifdef CONFIG_LV_PERF_MONITOR_ALIGN_TOP_LEFT
# define CONFIG_LV_USE_PERF_MONITOR_POS LV_ALIGN_TOP_LEFT
#elif defined(CONFIG_LV_USE_PERF_MONITOR_ALIGN_TOP_MID)
# define CONFIG_LV_USE_PERF_MONITOR_POS LV_ALIGN_TOP_MID
#elif defined(CONFIG_LV_PERF_MONITOR_ALIGN_TOP_RIGHT)
# define CONFIG_LV_USE_PERF_MONITOR_POS LV_ALIGN_TOP_RIGHT
#elif defined(CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_LEFT)
# define CONFIG_LV_USE_PERF_MONITOR_POS LV_ALIGN_BOTTOM_LEFT
#elif defined(CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_MID)
# define CONFIG_LV_USE_PERF_MONITOR_POS LV_ALIGN_BOTTOM_MID
#elif defined(CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_RIGHT)
# define CONFIG_LV_USE_PERF_MONITOR_POS LV_ALIGN_BOTTOM_RIGHT
#elif defined(CONFIG_LV_PERF_MONITOR_ALIGN_LEFT_MID)
# define CONFIG_LV_USE_PERF_MONITOR_POS LV_ALIGN_LEFT_MID
#elif defined(CONFIG_LV_PERF_MONITOR_ALIGN_RIGHT_MID)
# define CONFIG_LV_USE_PERF_MONITOR_POS LV_ALIGN_RIGHT_MID
#elif defined(CONFIG_LV_PERF_MONITOR_ALIGN_CENTER)
# define CONFIG_LV_USE_PERF_MONITOR_POS LV_ALIGN_CENTER
#endif
#ifdef CONFIG_LV_MEM_MONITOR_ALIGN_TOP_LEFT
# define CONFIG_LV_USE_MEM_MONITOR_POS LV_ALIGN_TOP_LEFT
#elif defined(CONFIG_LV_USE_MEM_MONITOR_ALIGN_TOP_MID)
# define CONFIG_LV_USE_MEM_MONITOR_POS LV_ALIGN_TOP_MID
#elif defined(CONFIG_LV_MEM_MONITOR_ALIGN_TOP_RIGHT)
# define CONFIG_LV_USE_MEM_MONITOR_POS LV_ALIGN_TOP_RIGHT
#elif defined(CONFIG_LV_MEM_MONITOR_ALIGN_BOTTOM_LEFT)
# define CONFIG_LV_USE_MEM_MONITOR_POS LV_ALIGN_BOTTOM_LEFT
#elif defined(CONFIG_LV_MEM_MONITOR_ALIGN_BOTTOM_MID)
# define CONFIG_LV_USE_MEM_MONITOR_POS LV_ALIGN_BOTTOM_MID
#elif defined(CONFIG_LV_MEM_MONITOR_ALIGN_BOTTOM_RIGHT)
# define CONFIG_LV_USE_MEM_MONITOR_POS LV_ALIGN_BOTTOM_RIGHT
#elif defined(CONFIG_LV_MEM_MONITOR_ALIGN_LEFT_MID)
# define CONFIG_LV_USE_MEM_MONITOR_POS LV_ALIGN_LEFT_MID
#elif defined(CONFIG_LV_MEM_MONITOR_ALIGN_RIGHT_MID)
# define CONFIG_LV_USE_MEM_MONITOR_POS LV_ALIGN_RIGHT_MID
#elif defined(CONFIG_LV_MEM_MONITOR_ALIGN_CENTER)
# define CONFIG_LV_USE_MEM_MONITOR_POS LV_ALIGN_CENTER
#endif
/********************
* FONT SELECTION
*******************/
/**
* NOTE: In Kconfig instead of `LV_DEFAULT_FONT`
* `CONFIG_LV_FONT_DEFAULT_<font_name>` is defined
* hence the large selection with if-s
*/
/*------------------
* DEFAULT FONT
*-----------------*/
#ifdef CONFIG_LV_FONT_DEFAULT_MONTSERRAT_8
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_8
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_10)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_10
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_12)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_12
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_14)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_14
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_16)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_16
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_18)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_18
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_20)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_20
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_22)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_22
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_24)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_24
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_26)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_26
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_28
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_30)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_30
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_32)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_32
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_34)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_34
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_36)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_36
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_38)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_38
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_40)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_40
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_42)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_42
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_44)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_44
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_46)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_46
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_48)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_48
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_12_SUBPX)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_12_subpx
#elif defined(CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28_COMPRESSED)
# define CONFIG_LV_FONT_DEFAULT &lv_font_montserrat_28_compressed
#elif defined(CONFIG_LV_FONT_DEFAULT_DEJAVU_16_PERSIAN_HEBREW)
# define CONFIG_LV_FONT_DEFAULT &lv_font_dejavu_16_persian_hebrew
#elif defined(CONFIG_LV_FONT_DEFAULT_SIMSUN_16_CJK)
# define CONFIG_LV_FONT_DEFAULT &lv_font_simsun_16_cjk
#elif defined(CONFIG_LV_FONT_DEFAULT_UNSCII_8)
# define CONFIG_LV_FONT_DEFAULT &lv_font_unscii_8
#elif defined(CONFIG_LV_FONT_DEFAULT_UNSCII_16)
# define CONFIG_LV_FONT_DEFAULT &lv_font_unscii_16
#endif
/*------------------
* TEXT ENCODING
*-----------------*/
#ifdef CONFIG_LV_TXT_ENC_UTF8
# define CONFIG_LV_TXT_ENC LV_TXT_ENC_UTF8
#elif defined(CONFIG_LV_TXT_ENC_ASCII)
# define CONFIG_LV_TXT_ENC LV_TXT_ENC_ASCII
#endif
/*------------------
* BIDI DIRECTION
*-----------------*/
// #ifdef CONFIG_LV_BASE_DIR_LTR
# define CONFIG_LV_BIDI_BASE_DIR_DEF LV_BASE_DIR_LTR
// #elif defined(CONFIG_LV_BASE_DIR_RTL)
// # define CONFIG_LV_BIDI_BASE_DIR_DEF LV_BASE_DIR_RTL
// #elif defined(CONFIG_LV_BASE_DIR_AUTO)
// # define CONFIG_LV_BIDI_BASE_DIR_DEF LV_BASE_DIR_AUTO
// #endif
/*------------------
* LINUX FBDEV
*-----------------*/
#ifdef CONFIG_LV_LINUX_FBDEV_RENDER_MODE_PARTIAL
# define CONFIG_LV_LINUX_FBDEV_RENDER_MODE LV_DISPLAY_RENDER_MODE_PARTIAL
#elif defined(CONFIG_LV_LINUX_FBDEV_RENDER_MODE_DIRECT)
# define CONFIG_LV_LINUX_FBDEV_RENDER_MODE LV_DISPLAY_RENDER_MODE_DIRECT
#elif defined(CONFIG_LV_LINUX_FBDEV_RENDER_MODE_FULL)
# define CONFIG_LV_LINUX_FBDEV_RENDER_MODE LV_DISPLAY_RENDER_MODE_FULL
#endif
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_CONF_KCONFIG_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_mask.c | /**
* @file lv_draw_mask.c
*
*/
/*********************
* INCLUDES
*********************/
#include <stdbool.h>
#include "lv_draw_mask.h"
#include "../core/lv_refr.h"
#include "../misc/lv_math.h"
#include "../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
LV_ATTRIBUTE_FAST_MEM void lv_draw_mask_rect_dsc_init(lv_draw_mask_rect_dsc_t * dsc)
{
lv_memzero(dsc, sizeof(lv_draw_mask_rect_dsc_t));
}
LV_ATTRIBUTE_FAST_MEM void lv_draw_mask_rect(struct _lv_layer_t * layer, const lv_draw_mask_rect_dsc_t * dsc)
{
if(!lv_color_format_has_alpha(layer->color_format)) {
LV_LOG_WARN("Only layers with alpha channel can be masked");
return;
}
lv_draw_task_t * t = lv_draw_add_task(layer, &layer->buf_area);
t->draw_dsc = lv_malloc(sizeof(*dsc));
lv_memcpy(t->draw_dsc, dsc, sizeof(*dsc));
t->type = LV_DRAW_TASK_TYPE_MASK_RECTANGLE;
lv_draw_dsc_base_t * base_dsc = t->draw_dsc;
base_dsc->layer = layer;
if(base_dsc->obj && lv_obj_has_flag(base_dsc->obj, LV_OBJ_FLAG_SEND_DRAW_TASK_EVENTS)) {
/*Disable sending LV_EVENT_DRAW_TASK_ADDED first to avoid triggering recursive
*event calls due draw task adds in the event*/
lv_obj_remove_flag(base_dsc->obj, LV_OBJ_FLAG_SEND_DRAW_TASK_EVENTS);
lv_obj_send_event(dsc->base.obj, LV_EVENT_DRAW_TASK_ADDED, t);
lv_obj_add_flag(base_dsc->obj, LV_OBJ_FLAG_SEND_DRAW_TASK_EVENTS);
}
lv_draw_dispatch();
}
/**********************
* STATIC FUNCTIONS
**********************/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_triangle.c | /**
* @file lv_draw_triangle.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../core/lv_obj.h"
#include "lv_draw_triangle.h"
#include "../misc/lv_math.h"
#include "../stdlib/lv_mem.h"
#include "../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_triangle_dsc_init(lv_draw_triangle_dsc_t * dsc)
{
LV_PROFILER_BEGIN;
lv_memzero(dsc, sizeof(lv_draw_triangle_dsc_t));
dsc->bg_color = lv_color_white();
dsc->bg_grad.stops[0].color = lv_color_white();
dsc->bg_grad.stops[1].color = lv_color_black();
dsc->bg_grad.stops[1].frac = 0xFF;
dsc->bg_grad.stops_count = 2;
dsc->bg_opa = LV_OPA_COVER;
LV_PROFILER_END;
}
void lv_draw_triangle(struct _lv_layer_t * layer, const lv_draw_triangle_dsc_t * dsc)
{
LV_PROFILER_BEGIN;
lv_area_t a;
a.x1 = (int32_t)LV_MIN3(dsc->p[0].x, dsc->p[1].x, dsc->p[2].x);
a.y1 = (int32_t)LV_MIN3(dsc->p[0].y, dsc->p[1].y, dsc->p[2].y);
a.x2 = (int32_t)LV_MAX3(dsc->p[0].x, dsc->p[1].x, dsc->p[2].x);
a.y2 = (int32_t)LV_MAX3(dsc->p[0].y, dsc->p[1].y, dsc->p[2].y);
lv_draw_task_t * t = lv_draw_add_task(layer, &a);
t->draw_dsc = lv_malloc(sizeof(*dsc));
lv_memcpy(t->draw_dsc, dsc, sizeof(*dsc));
t->type = LV_DRAW_TASK_TYPE_TRIANGLE;
lv_draw_finalize_task_creation(layer, t);
LV_PROFILER_END;
}
/**********************
* STATIC FUNCTIONS
**********************/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_mask.h | /**
* @file lv_draw_mask_rect.h
*
*/
#ifndef LV_DRAW_MASK_RECT_H
#define LV_DRAW_MASK_RECT_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "lv_draw.h"
#include "../misc/lv_color.h"
#include "../misc/lv_area.h"
#include "../misc/lv_style.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_draw_dsc_base_t base;
lv_area_t area;
int32_t radius;
} lv_draw_mask_rect_dsc_t;
struct _lv_layer_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
LV_ATTRIBUTE_FAST_MEM void lv_draw_mask_rect_dsc_init(lv_draw_mask_rect_dsc_t * dsc);
/**
* Draw a line
* @param point1 first point of the line
* @param point2 second point of the line
* @param clip the line will be drawn only in this area
* @param dsc pointer to an initialized `lv_draw_line_dsc_t` variable
*/
void lv_draw_mask_rect(struct _lv_layer_t * layer, const lv_draw_mask_rect_dsc_t * dsc);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_MASK_RECT_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_line.h | /**
* @file lv_draw_line.h
*
*/
#ifndef LV_DRAW_LINE_H
#define LV_DRAW_LINE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#include "../misc/lv_color.h"
#include "../misc/lv_area.h"
#include "../misc/lv_style.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_draw_dsc_base_t base;
lv_value_precise_t p1_x;
lv_value_precise_t p1_y;
lv_value_precise_t p2_x;
lv_value_precise_t p2_y;
lv_color_t color;
int32_t width;
int32_t dash_width;
int32_t dash_gap;
lv_opa_t opa;
lv_blend_mode_t blend_mode : 2;
uint8_t round_start : 1;
uint8_t round_end : 1;
uint8_t raw_end : 1; /*Do not bother with perpendicular line ending if it's not visible for any reason*/
} lv_draw_line_dsc_t;
struct _lv_layer_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
LV_ATTRIBUTE_FAST_MEM void lv_draw_line_dsc_init(lv_draw_line_dsc_t * dsc);
/**
* Draw a line
* @param layer pointer to a layer
* @param dsc pointer to an initialized `lv_draw_line_dsc_t` variable
*/
void lv_draw_line(struct _lv_layer_t * layer, const lv_draw_line_dsc_t * dsc);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_LINE_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_triangle.h | /**
* @file lv_draw_triangle.h
*
*/
#ifndef LV_DRAW_TRIANGLE_H
#define LV_DRAW_TRIANGLE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "lv_draw_rect.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_draw_dsc_base_t base;
lv_opa_t bg_opa;
lv_color_t bg_color;
lv_grad_dsc_t bg_grad;
lv_point_precise_t p[3];
} lv_draw_triangle_dsc_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
void lv_draw_triangle_dsc_init(lv_draw_triangle_dsc_t * draw_dsc);
void lv_draw_triangle(struct _lv_layer_t * layer, const lv_draw_triangle_dsc_t * draw_dsc);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_TRIANGLE_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_image.h | /**
* @file lv_draw_img.h
*
*/
#ifndef LV_DRAW_IMAGE_H
#define LV_DRAW_IMAGE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "lv_draw.h"
#include "lv_image_decoder.h"
#include "lv_image_buf.h"
#include "../misc/lv_style.h"
/*********************
* DEFINES
*********************/
/**********************
* MACROS
**********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_color_t alpha_color;
const lv_color32_t * palette;
uint32_t palette_size : 9;
} lv_draw_image_sup_t;
typedef struct _lv_draw_image_dsc_t {
lv_draw_dsc_base_t base;
const void * src;
lv_image_header_t header;
int32_t rotation;
int32_t scale_x;
int32_t scale_y;
lv_point_t pivot;
lv_color_t recolor;
lv_opa_t recolor_opa;
lv_opa_t opa;
lv_blend_mode_t blend_mode : 4;
int32_t frame_id;
uint16_t antialias : 1;
lv_draw_image_sup_t * sup;
} lv_draw_image_dsc_t;
struct _lv_layer_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
void lv_draw_image_dsc_init(lv_draw_image_dsc_t * dsc);
/**
* Draw an image
* @param layer pointer to a layer
* @param dsc pointer to an initialized `lv_draw_image_dsc_t` variable
* @param coords the coordinates of the image
*/
void lv_draw_image(struct _lv_layer_t * layer, const lv_draw_image_dsc_t * dsc, const lv_area_t * coords);
/**
* Draw a layer on an other layer
* @param layer pointer to a layer
* @param dsc pointer to an initialized `lv_draw_image_dsc_t` variable
* @param coords the coordinates of the layer
*/
void lv_draw_layer(struct _lv_layer_t * layer, const lv_draw_image_dsc_t * dsc, const lv_area_t * coords);
/**
* Get the type of an image source
* @param src pointer to an image source:
* - pointer to an 'lv_image_t' variable (image stored internally and compiled into the code)
* - a path to a file (e.g. "S:/folder/image.bin")
* - or a symbol (e.g. LV_SYMBOL_CLOSE)
* @return type of the image source LV_IMAGE_SRC_VARIABLE/FILE/SYMBOL/UNKNOWN
*/
lv_image_src_t lv_image_src_get_type(const void * src);
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_IMAGE_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw.c | /**
* @file lv_draw.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_draw.h"
#include "sw/lv_draw_sw.h"
#include "../display/lv_display_private.h"
#include "../core/lv_global.h"
#include "../core/lv_refr.h"
#include "../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
#define _draw_info LV_GLOBAL_DEFAULT()->draw_info
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static bool is_independent(lv_layer_t * layer, lv_draw_task_t * t_check);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_init(void)
{
#if LV_USE_OS
lv_thread_sync_init(&_draw_info.sync);
#endif
}
void * lv_draw_create_unit(size_t size)
{
lv_draw_unit_t * new_unit = lv_malloc(size);
lv_memzero(new_unit, size);
new_unit->next = _draw_info.unit_head;
_draw_info.unit_head = new_unit;
return new_unit;
}
lv_draw_task_t * lv_draw_add_task(lv_layer_t * layer, const lv_area_t * coords)
{
LV_PROFILER_BEGIN;
lv_draw_task_t * new_task = lv_malloc(sizeof(lv_draw_task_t));
lv_memzero(new_task, sizeof(*new_task));
new_task->area = *coords;
new_task->clip_area = layer->clip_area;
new_task->state = LV_DRAW_TASK_STATE_QUEUED;
/*Find the tail*/
if(layer->draw_task_head == NULL) {
layer->draw_task_head = new_task;
}
else {
lv_draw_task_t * tail = layer->draw_task_head;
while(tail->next) tail = tail->next;
tail->next = new_task;
}
LV_PROFILER_END;
return new_task;
}
void lv_draw_finalize_task_creation(lv_layer_t * layer, lv_draw_task_t * t)
{
lv_draw_dsc_base_t * base_dsc = t->draw_dsc;
base_dsc->layer = layer;
lv_draw_global_info_t * info = &_draw_info;
/*Send LV_EVENT_DRAW_TASK_ADDED and dispatch only on the "main" draw_task
*and not on the draw tasks added in the event.
*Sending LV_EVENT_DRAW_TASK_ADDED events might cause recursive event sends
*Dispatching might remove the "main" draw task while it's still being used in the event*/
if(info->task_running == false) {
info->task_running = true;
if(base_dsc->obj && lv_obj_has_flag(base_dsc->obj, LV_OBJ_FLAG_SEND_DRAW_TASK_EVENTS)) {
lv_obj_send_event(base_dsc->obj, LV_EVENT_DRAW_TASK_ADDED, t);
}
/*Let the draw units set their preference score*/
t->preference_score = 100;
t->preferred_draw_unit_id = 0;
lv_draw_unit_t * u = info->unit_head;
while(u) {
if(u->evaluate_cb) u->evaluate_cb(u, t);
u = u->next;
}
lv_draw_dispatch();
info->task_running = false;
}
else {
/*Let the draw units set their preference score*/
t->preference_score = 100;
t->preferred_draw_unit_id = 0;
lv_draw_unit_t * u = info->unit_head;
while(u) {
if(u->evaluate_cb) u->evaluate_cb(u, t);
u = u->next;
}
}
}
void lv_draw_dispatch(void)
{
LV_PROFILER_BEGIN;
bool one_taken = false;
lv_display_t * disp = lv_display_get_next(NULL);
while(disp) {
lv_layer_t * layer = disp->layer_head;
while(layer) {
bool ret = lv_draw_dispatch_layer(disp, layer);
if(ret) one_taken = true;
layer = layer->next;
}
if(!one_taken) {
lv_draw_dispatch_request();
}
disp = lv_display_get_next(disp);
}
LV_PROFILER_END;
}
bool lv_draw_dispatch_layer(struct _lv_display_t * disp, lv_layer_t * layer)
{
/*Remove the finished tasks first*/
lv_draw_task_t * t_prev = NULL;
lv_draw_task_t * t = layer->draw_task_head;
while(t) {
lv_draw_task_t * t_next = t->next;
if(t->state == LV_DRAW_TASK_STATE_READY) {
if(t_prev) t_prev->next = t->next; /*Remove by it by assigning the next task to the previous*/
else layer->draw_task_head = t_next; /*If it was the head, set the next as head*/
/*If it was layer drawing free the layer too*/
if(t->type == LV_DRAW_TASK_TYPE_LAYER) {
lv_draw_image_dsc_t * draw_image_dsc = t->draw_dsc;
lv_layer_t * layer_drawn = (lv_layer_t *)draw_image_dsc->src;
if(layer_drawn->buf) {
int32_t h = lv_area_get_height(&layer_drawn->buf_area);
int32_t w = lv_area_get_width(&layer_drawn->buf_area);
uint32_t layer_size_byte = h * lv_draw_buf_width_to_stride(w, layer_drawn->color_format);
_draw_info.used_memory_for_layers_kb -= layer_size_byte < 1024 ? 1 : layer_size_byte >> 10;
LV_LOG_INFO("Layer memory used: %d kB\n", _draw_info.used_memory_for_layers_kb);
lv_draw_buf_free(layer_drawn->buf_unaligned);
}
/*Remove the layer from the display's*/
if(disp) {
lv_layer_t * l2 = disp->layer_head;
while(l2) {
if(l2->next == layer_drawn) {
l2->next = layer_drawn->next;
break;
}
l2 = l2->next;
}
if(disp->layer_deinit) disp->layer_deinit(disp, layer_drawn);
lv_free(layer_drawn);
}
}
if(t->type == LV_DRAW_TASK_TYPE_LABEL) {
lv_draw_label_dsc_t * draw_label_dsc = t->draw_dsc;
if(draw_label_dsc->text_local) {
lv_free((void *)draw_label_dsc->text);
draw_label_dsc->text = NULL;
}
}
lv_free(t->draw_dsc);
lv_free(t);
}
else {
t_prev = t;
}
t = t_next;
}
bool one_taken = false;
/*This layer is ready, enable blending its buffer*/
if(layer->parent && layer->all_tasks_added && layer->draw_task_head == NULL) {
/*Find a draw task with TYPE_LAYER in the layer where the src is this layer*/
lv_draw_task_t * t_src = layer->parent->draw_task_head;
while(t_src) {
if(t_src->type == LV_DRAW_TASK_TYPE_LAYER && t_src->state == LV_DRAW_TASK_STATE_WAITING) {
lv_draw_image_dsc_t * draw_dsc = t_src->draw_dsc;
if(draw_dsc->src == layer) {
t_src->state = LV_DRAW_TASK_STATE_QUEUED;
lv_draw_dispatch_request();
break;
}
}
t_src = t_src->next;
}
}
/*Assign draw tasks to the draw_units*/
else {
bool layer_ok = true;
if(layer->buf == NULL) {
int32_t h = lv_area_get_height(&layer->buf_area);
int32_t w = lv_area_get_width(&layer->buf_area);
uint32_t layer_size_byte = h * lv_draw_buf_width_to_stride(w, layer->color_format);
uint32_t kb = layer_size_byte < 1024 ? 1 : layer_size_byte >> 10;
if(_draw_info.used_memory_for_layers_kb + kb > LV_LAYER_MAX_MEMORY_USAGE) {
layer_ok = false;
}
}
if(layer_ok) {
/*Find a draw unit which is not busy and can take at least one task*/
/*Let all draw units to pick draw tasks*/
lv_draw_unit_t * u = _draw_info.unit_head;
while(u) {
int32_t taken_cnt = u->dispatch_cb(u, layer);
if(taken_cnt < 0) {
break;
}
if(taken_cnt > 0) one_taken = true;
u = u->next;
}
}
}
return one_taken;
}
void lv_draw_dispatch_wait_for_request(void)
{
#if LV_USE_OS
lv_thread_sync_wait(&_draw_info.sync);
#else
while(!_draw_info.dispatch_req);
_draw_info.dispatch_req = 0;
#endif
}
void lv_draw_dispatch_request(void)
{
#if LV_USE_OS
lv_thread_sync_signal(&_draw_info.sync);
#else
_draw_info.dispatch_req = 1;
#endif
}
lv_draw_task_t * lv_draw_get_next_available_task(lv_layer_t * layer, lv_draw_task_t * t_prev, uint8_t draw_unit_id)
{
LV_PROFILER_BEGIN;
/*If the first task is screen sized, there cannot be independent areas*/
if(layer->draw_task_head) {
int32_t hor_res = lv_display_get_horizontal_resolution(_lv_refr_get_disp_refreshing());
int32_t ver_res = lv_display_get_vertical_resolution(_lv_refr_get_disp_refreshing());
lv_draw_task_t * t = layer->draw_task_head;
if(t->state != LV_DRAW_TASK_STATE_QUEUED &&
t->area.x1 <= 0 && t->area.x2 >= hor_res - 1 &&
t->area.y1 <= 0 && t->area.y2 >= ver_res - 1) {
LV_PROFILER_END;
return NULL;
}
}
lv_draw_task_t * t = t_prev ? t_prev->next : layer->draw_task_head;
while(t) {
/*Find a queued and independent task*/
if(t->state == LV_DRAW_TASK_STATE_QUEUED &&
(t->preferred_draw_unit_id == LV_DRAW_UNIT_ID_ANY || t->preferred_draw_unit_id == draw_unit_id) &&
is_independent(layer, t)) {
LV_PROFILER_END;
return t;
}
t = t->next;
}
LV_PROFILER_END;
return NULL;
}
lv_layer_t * lv_draw_layer_create(lv_layer_t * parent_layer, lv_color_format_t color_format, const lv_area_t * area)
{
lv_display_t * disp = _lv_refr_get_disp_refreshing();
lv_layer_t * new_layer = lv_malloc(sizeof(lv_layer_t));
LV_ASSERT_MALLOC(new_layer);
if(new_layer == NULL) return NULL;
lv_memzero(new_layer, sizeof(lv_layer_t));
new_layer->parent = parent_layer;
new_layer->clip_area = *area;
new_layer->buf_area = *area;
new_layer->color_format = color_format;
if(disp->layer_head) {
lv_layer_t * tail = disp->layer_head;
while(tail->next) tail = tail->next;
tail->next = new_layer;
}
else {
disp->layer_head = new_layer;
}
return new_layer;
}
void * lv_draw_layer_alloc_buf(lv_layer_t * layer)
{
/*If the buffer of the layer is not allocated yet, allocate it now*/
if(layer->buf == NULL) {
int32_t w = lv_area_get_width(&layer->buf_area);
int32_t h = lv_area_get_height(&layer->buf_area);
int32_t stride = lv_draw_buf_width_to_stride(w, layer->color_format);
uint32_t layer_size_byte = h * stride;
layer->buf_unaligned = lv_draw_buf_malloc(layer_size_byte, layer->color_format);
if(layer->buf_unaligned == NULL) {
LV_LOG_WARN("Allocating %"LV_PRIu32" bytes of layer buffer failed. Try later", layer_size_byte);
return NULL;
}
layer->buf = lv_draw_buf_align(layer->buf_unaligned, layer->color_format);
uint32_t kb = layer_size_byte < 1024 ? 1 : layer_size_byte >> 10;
_draw_info.used_memory_for_layers_kb += kb;
LV_LOG_INFO("Layer memory used: %d kB\n", _draw_info.used_memory_for_layers_kb);
if(lv_color_format_has_alpha(layer->color_format)) {
lv_area_t a;
a.x1 = 0;
a.y1 = 0;
a.x2 = w - 1;
a.y2 = h - 1;
lv_draw_buf_clear(layer->buf, w, h, layer->color_format, &a);
}
}
return lv_draw_buf_align(layer->buf, layer->color_format);
}
void * lv_draw_layer_go_to_xy(lv_layer_t * layer, int32_t x, int32_t y)
{
uint32_t stride = lv_draw_buf_width_to_stride(lv_area_get_width(&layer->buf_area), layer->color_format);
return lv_draw_buf_go_to_xy(layer->buf, stride, layer->color_format, x, y);
}
/**********************
* STATIC FUNCTIONS
**********************/
/**
* Check if there are older draw task overlapping the area of `t_check`
* @param layer the draw ctx to search in
* @param t_check check this task if it overlaps with the older ones
* @return true: `t_check` is not overlapping with older tasks so it's independent
*/
static bool is_independent(lv_layer_t * layer, lv_draw_task_t * t_check)
{
LV_PROFILER_BEGIN;
lv_draw_task_t * t = layer->draw_task_head;
/*If t_check is outside of the older tasks then it's independent*/
while(t && t != t_check) {
if(t->state != LV_DRAW_TASK_STATE_READY) {
lv_area_t a;
if(_lv_area_intersect(&a, &t->area, &t_check->area)) {
LV_PROFILER_END;
return false;
}
}
t = t->next;
}
LV_PROFILER_END;
return true;
}
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_arc.c | /**
* @file lv_draw_arc.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../core/lv_obj.h"
#include "lv_draw_arc.h"
#include "../core/lv_obj_event.h"
#include "../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_arc_dsc_init(lv_draw_arc_dsc_t * dsc)
{
lv_memzero(dsc, sizeof(lv_draw_arc_dsc_t));
dsc->width = 1;
dsc->opa = LV_OPA_COVER;
dsc->color = lv_color_black();
}
void lv_draw_arc(lv_layer_t * layer, const lv_draw_arc_dsc_t * dsc)
{
if(dsc->opa <= LV_OPA_MIN) return;
if(dsc->width == 0) return;
if(dsc->start_angle == dsc->end_angle) return;
LV_PROFILER_BEGIN;
lv_area_t a;
a.x1 = dsc->center.x - dsc->radius;
a.y1 = dsc->center.y - dsc->radius;
a.x2 = dsc->center.x + dsc->radius - 1;
a.y2 = dsc->center.y + dsc->radius - 1;
lv_draw_task_t * t = lv_draw_add_task(layer, &a);
t->draw_dsc = lv_malloc(sizeof(*dsc));
lv_memcpy(t->draw_dsc, dsc, sizeof(*dsc));
t->type = LV_DRAW_TASK_TYPE_ARC;
lv_draw_finalize_task_creation(layer, t);
LV_PROFILER_END;
}
void lv_draw_arc_get_area(int32_t x, int32_t y, uint16_t radius, lv_value_precise_t start_angle,
lv_value_precise_t end_angle,
int32_t w, bool rounded, lv_area_t * area)
{
int32_t rout = radius;
int32_t start_angle_int = (int32_t) start_angle;
int32_t end_angle_int = (int32_t) end_angle;
/*Special case: full arc invalidation */
if(end_angle_int == start_angle_int + 360) {
area->x1 = x - rout;
area->y1 = y - rout;
area->x2 = x + rout;
area->y2 = y + rout;
return;
}
if(start_angle_int > 360) start_angle_int -= 360;
if(end_angle_int > 360) end_angle_int -= 360;
int32_t rin = radius - w;
int32_t extra_area = rounded ? w / 2 + 1 : 0;
uint8_t start_quarter = start_angle_int / 90;
uint8_t end_quarter = end_angle_int / 90;
/*360 deg still counts as quarter 3 (360 / 90 would be 4)*/
if(start_quarter == 4) start_quarter = 3;
if(end_quarter == 4) end_quarter = 3;
if(start_quarter == end_quarter && start_angle_int <= end_angle_int) {
if(start_quarter == 0) {
area->y1 = y + ((lv_trigo_sin(start_angle_int) * rin) >> LV_TRIGO_SHIFT) - extra_area;
area->x2 = x + ((lv_trigo_sin(start_angle_int + 90) * rout) >> LV_TRIGO_SHIFT) + extra_area;
area->y2 = y + ((lv_trigo_sin(end_angle_int) * rout) >> LV_TRIGO_SHIFT) + extra_area;
area->x1 = x + ((lv_trigo_sin(end_angle_int + 90) * rin) >> LV_TRIGO_SHIFT) - extra_area;
}
else if(start_quarter == 1) {
area->y2 = y + ((lv_trigo_sin(start_angle_int) * rout) >> LV_TRIGO_SHIFT) + extra_area;
area->x2 = x + ((lv_trigo_sin(start_angle_int + 90) * rin) >> LV_TRIGO_SHIFT) + extra_area;
area->y1 = y + ((lv_trigo_sin(end_angle_int) * rin) >> LV_TRIGO_SHIFT) - extra_area;
area->x1 = x + ((lv_trigo_sin(end_angle_int + 90) * rout) >> LV_TRIGO_SHIFT) - extra_area;
}
else if(start_quarter == 2) {
area->x1 = x + ((lv_trigo_sin(start_angle_int + 90) * rout) >> LV_TRIGO_SHIFT) - extra_area;
area->y2 = y + ((lv_trigo_sin(start_angle_int) * rin) >> LV_TRIGO_SHIFT) + extra_area;
area->y1 = y + ((lv_trigo_sin(end_angle_int) * rout) >> LV_TRIGO_SHIFT) - extra_area;
area->x2 = x + ((lv_trigo_sin(end_angle_int + 90) * rin) >> LV_TRIGO_SHIFT) + extra_area;
}
else if(start_quarter == 3) {
area->x1 = x + ((lv_trigo_sin(start_angle_int + 90) * rin) >> LV_TRIGO_SHIFT) - extra_area;
area->y1 = y + ((lv_trigo_sin(start_angle_int) * rout) >> LV_TRIGO_SHIFT) - extra_area;
area->x2 = x + ((lv_trigo_sin(end_angle_int + 90) * rout) >> LV_TRIGO_SHIFT) + extra_area;
area->y2 = y + ((lv_trigo_sin(end_angle_int) * rin) >> LV_TRIGO_SHIFT) + extra_area;
}
}
else if(start_quarter == 0 && end_quarter == 1) {
area->x1 = x + ((lv_trigo_sin(end_angle_int + 90) * rout) >> LV_TRIGO_SHIFT) - extra_area;
area->y1 = y + ((LV_MIN(lv_trigo_sin(end_angle_int),
lv_trigo_sin(start_angle_int)) * rin) >> LV_TRIGO_SHIFT) - extra_area;
area->x2 = x + ((lv_trigo_sin(start_angle_int + 90) * rout) >> LV_TRIGO_SHIFT) + extra_area;
area->y2 = y + rout + extra_area;
}
else if(start_quarter == 1 && end_quarter == 2) {
area->x1 = x - rout - extra_area;
area->y1 = y + ((lv_trigo_sin(end_angle_int) * rout) >> LV_TRIGO_SHIFT) - extra_area;
area->x2 = x + ((LV_MAX(lv_trigo_sin(start_angle_int + 90),
lv_trigo_sin(end_angle_int + 90)) * rin) >> LV_TRIGO_SHIFT) + extra_area;
area->y2 = y + ((lv_trigo_sin(start_angle_int) * rout) >> LV_TRIGO_SHIFT) + extra_area;
}
else if(start_quarter == 2 && end_quarter == 3) {
area->x1 = x + ((lv_trigo_sin(start_angle_int + 90) * rout) >> LV_TRIGO_SHIFT) - extra_area;
area->y1 = y - rout - extra_area;
area->x2 = x + ((lv_trigo_sin(end_angle_int + 90) * rout) >> LV_TRIGO_SHIFT) + extra_area;
area->y2 = y + (LV_MAX(lv_trigo_sin(end_angle_int) * rin,
lv_trigo_sin(start_angle_int) * rin) >> LV_TRIGO_SHIFT) + extra_area;
}
else if(start_quarter == 3 && end_quarter == 0) {
area->x1 = x + ((LV_MIN(lv_trigo_sin(end_angle_int + 90),
lv_trigo_sin(start_angle_int + 90)) * rin) >> LV_TRIGO_SHIFT) - extra_area;
area->y1 = y + ((lv_trigo_sin(start_angle_int) * rout) >> LV_TRIGO_SHIFT) - extra_area;
area->x2 = x + rout + extra_area;
area->y2 = y + ((lv_trigo_sin(end_angle_int) * rout) >> LV_TRIGO_SHIFT) + extra_area;
}
else {
area->x1 = x - rout;
area->y1 = y - rout;
area->x2 = x + rout;
area->y2 = y + rout;
}
}
/**********************
* STATIC FUNCTIONS
**********************/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_rect.c | /**
* @file lv_draw_rect.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../core/lv_obj.h"
#include "lv_draw_rect.h"
#include "../misc/lv_assert.h"
#include "../core/lv_obj_event.h"
#include "../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
LV_ATTRIBUTE_FAST_MEM void lv_draw_rect_dsc_init(lv_draw_rect_dsc_t * dsc)
{
lv_memzero(dsc, sizeof(lv_draw_rect_dsc_t));
dsc->bg_color = lv_color_white();
dsc->bg_grad.stops[0].color = lv_color_white();
dsc->bg_grad.stops[1].color = lv_color_black();
dsc->bg_grad.stops[1].frac = 0xFF;
dsc->bg_grad.stops_count = 2;
dsc->border_color = lv_color_black();
dsc->shadow_color = lv_color_black();
dsc->bg_image_symbol_font = LV_FONT_DEFAULT;
dsc->bg_opa = LV_OPA_COVER;
dsc->bg_image_opa = LV_OPA_COVER;
dsc->outline_opa = LV_OPA_COVER;
dsc->border_opa = LV_OPA_COVER;
dsc->shadow_opa = LV_OPA_COVER;
dsc->border_side = LV_BORDER_SIDE_FULL;
}
void lv_draw_fill_dsc_init(lv_draw_fill_dsc_t * dsc)
{
lv_memzero(dsc, sizeof(*dsc));
dsc->opa = LV_OPA_COVER;
}
void lv_draw_border_dsc_init(lv_draw_border_dsc_t * dsc)
{
lv_memzero(dsc, sizeof(*dsc));
dsc->opa = LV_OPA_COVER;
dsc->side = LV_BORDER_SIDE_FULL;
}
void lv_draw_box_shadow_dsc_init(lv_draw_box_shadow_dsc_t * dsc)
{
lv_memzero(dsc, sizeof(*dsc));
dsc->opa = LV_OPA_COVER;
}
void lv_draw_bg_image_dsc_init(lv_draw_bg_image_dsc_t * dsc)
{
lv_memzero(dsc, sizeof(*dsc));
dsc->opa = LV_OPA_COVER;
}
void lv_draw_rect(lv_layer_t * layer, const lv_draw_rect_dsc_t * dsc, const lv_area_t * coords)
{
LV_PROFILER_BEGIN;
bool has_shadow;
bool has_fill;
bool has_border;
bool has_outline;
bool has_bg_img;
if(dsc->shadow_width == 0 ||
dsc->shadow_opa <= LV_OPA_MIN ||
(dsc->shadow_width == 1 && dsc->shadow_spread <= 0 &&
dsc->shadow_offset_x == 0 && dsc->shadow_offset_y == 0)) {
has_shadow = false;
}
else {
has_shadow = true;
}
if(dsc->bg_opa <= LV_OPA_MIN) has_fill = false;
else has_fill = true;
if(dsc->bg_image_opa <= LV_OPA_MIN || dsc->bg_image_src == NULL) has_bg_img = false;
else has_bg_img = true;
if(dsc->border_opa <= LV_OPA_MIN || dsc->border_width == 0 || dsc->border_post == true) has_border = false;
else has_border = true;
if(dsc->outline_opa <= LV_OPA_MIN || dsc->outline_width == 0) has_outline = false;
else has_outline = true;
bool bg_cover = true;
if(dsc->bg_opa < LV_OPA_COVER) bg_cover = false;
else if(dsc->bg_grad.dir != LV_GRAD_DIR_NONE) {
uint32_t s;
for(s = 0; s < dsc->bg_grad.stops_count; s++) {
if(dsc->bg_grad.stops[s].opa != LV_OPA_COVER) {
bg_cover = false;
break;
}
}
}
lv_draw_task_t * t;
/*Shadow*/
if(has_shadow) {
/*Check whether the shadow is visible*/
t = lv_draw_add_task(layer, coords);
lv_draw_box_shadow_dsc_t * shadow_dsc = lv_malloc(sizeof(lv_draw_box_shadow_dsc_t));
t->draw_dsc = shadow_dsc;
shadow_dsc->base = dsc->base;
shadow_dsc->radius = dsc->radius;
shadow_dsc->color = dsc->shadow_color;
shadow_dsc->width = dsc->shadow_width;
shadow_dsc->spread = dsc->shadow_spread;
shadow_dsc->opa = dsc->shadow_opa;
shadow_dsc->ofs_x = dsc->shadow_offset_x;
shadow_dsc->ofs_y = dsc->shadow_offset_y;
shadow_dsc->bg_cover = bg_cover;
t->type = LV_DRAW_TASK_TYPE_BOX_SHADOW;
lv_draw_finalize_task_creation(layer, t);
}
/*Background*/
if(has_fill) {
lv_area_t bg_coords = *coords;
/*If the border fully covers make the bg area 1px smaller to avoid artifacts on the corners*/
if(dsc->border_width > 1 && dsc->border_opa >= LV_OPA_MAX && dsc->radius != 0) {
bg_coords.x1 += (dsc->border_side & LV_BORDER_SIDE_LEFT) ? 1 : 0;
bg_coords.y1 += (dsc->border_side & LV_BORDER_SIDE_TOP) ? 1 : 0;
bg_coords.x2 -= (dsc->border_side & LV_BORDER_SIDE_RIGHT) ? 1 : 0;
bg_coords.y2 -= (dsc->border_side & LV_BORDER_SIDE_BOTTOM) ? 1 : 0;
}
t = lv_draw_add_task(layer, &bg_coords);
lv_draw_fill_dsc_t * bg_dsc = lv_malloc(sizeof(lv_draw_fill_dsc_t));
t->draw_dsc = bg_dsc;
bg_dsc->base = dsc->base;
bg_dsc->radius = dsc->radius;
bg_dsc->color = dsc->bg_color;
bg_dsc->grad = dsc->bg_grad;
bg_dsc->opa = dsc->bg_opa;
t->type = LV_DRAW_TASK_TYPE_FILL;
lv_draw_finalize_task_creation(layer, t);
}
/*Background image*/
if(has_bg_img) {
t = lv_draw_add_task(layer, coords);
lv_image_src_t src_type = lv_image_src_get_type(dsc->bg_image_src);
lv_result_t res = LV_RESULT_OK;
lv_image_header_t header;
if(src_type == LV_IMAGE_SRC_VARIABLE || src_type == LV_IMAGE_SRC_FILE) {
res = lv_image_decoder_get_info(dsc->bg_image_src, &header);
}
else if(src_type == LV_IMAGE_SRC_UNKNOWN) {
res = LV_RESULT_INVALID;
}
else {
lv_memzero(&header, sizeof(header));
}
if(res == LV_RESULT_OK) {
lv_draw_bg_image_dsc_t * bg_image_dsc = lv_malloc(sizeof(lv_draw_bg_image_dsc_t));
t->draw_dsc = bg_image_dsc;
bg_image_dsc->base = dsc->base;
bg_image_dsc->radius = dsc->radius;
bg_image_dsc->src = dsc->bg_image_src;
bg_image_dsc->font = dsc->bg_image_symbol_font;
bg_image_dsc->opa = dsc->bg_image_opa;
bg_image_dsc->recolor = dsc->bg_image_recolor;
bg_image_dsc->recolor_opa = dsc->bg_image_recolor_opa;
bg_image_dsc->tiled = dsc->bg_image_tiled;
bg_image_dsc->img_header = header;
t->type = LV_DRAW_TASK_TYPE_BG_IMG;
lv_draw_finalize_task_creation(layer, t);
}
}
/*Border*/
if(has_border) {
t = lv_draw_add_task(layer, coords);
lv_draw_border_dsc_t * border_dsc = lv_malloc(sizeof(lv_draw_border_dsc_t));
t->draw_dsc = border_dsc;
border_dsc->base = dsc->base;
border_dsc->radius = dsc->radius;
border_dsc->color = dsc->border_color;
border_dsc->opa = dsc->border_opa;
border_dsc->width = dsc->border_width;
border_dsc->side = dsc->border_side;
t->type = LV_DRAW_TASK_TYPE_BORDER;
lv_draw_finalize_task_creation(layer, t);
}
/*Outline*/
if(has_outline) {
lv_area_t outline_coords = *coords;
lv_area_increase(&outline_coords, dsc->outline_width + dsc->outline_pad, dsc->outline_width + dsc->outline_pad);
t = lv_draw_add_task(layer, &outline_coords);
lv_draw_border_dsc_t * outline_dsc = lv_malloc(sizeof(lv_draw_border_dsc_t));
t->draw_dsc = outline_dsc;
outline_dsc->base = dsc->base;
outline_dsc->radius = dsc->radius == LV_RADIUS_CIRCLE ? LV_RADIUS_CIRCLE : dsc->radius + dsc->outline_width +
dsc->outline_pad;
outline_dsc->color = dsc->outline_color;
outline_dsc->opa = dsc->outline_opa;
outline_dsc->width = dsc->outline_width;
outline_dsc->side = LV_BORDER_SIDE_FULL;
t->type = LV_DRAW_TASK_TYPE_BORDER;
lv_draw_finalize_task_creation(layer, t);
}
LV_ASSERT_MEM_INTEGRITY();
LV_PROFILER_END;
}
/**********************
* STATIC FUNCTIONS
**********************/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_image.c | /**
* @file lv_draw_img.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_draw_image.h"
#include "../display/lv_display.h"
#include "../misc/lv_log.h"
#include "../misc/lv_math.h"
#include "../core/lv_refr.h"
#include "../stdlib/lv_mem.h"
#include "../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_image_dsc_init(lv_draw_image_dsc_t * dsc)
{
lv_memzero(dsc, sizeof(lv_draw_image_dsc_t));
dsc->recolor = lv_color_black();
dsc->opa = LV_OPA_COVER;
dsc->scale_x = LV_SCALE_NONE;
dsc->scale_y = LV_SCALE_NONE;
dsc->antialias = LV_COLOR_DEPTH > 8 ? 1 : 0;
}
void lv_draw_layer(lv_layer_t * layer, const lv_draw_image_dsc_t * dsc, const lv_area_t * coords)
{
lv_draw_task_t * t = lv_draw_add_task(layer, coords);
t->draw_dsc = lv_malloc(sizeof(*dsc));
lv_memcpy(t->draw_dsc, dsc, sizeof(*dsc));
t->type = LV_DRAW_TASK_TYPE_LAYER;
t->state = LV_DRAW_TASK_STATE_WAITING;
lv_layer_t * layer_to_draw = (lv_layer_t *)dsc->src;
layer_to_draw->all_tasks_added = true;
lv_draw_finalize_task_creation(layer, t);
}
void lv_draw_image(lv_layer_t * layer, const lv_draw_image_dsc_t * dsc, const lv_area_t * coords)
{
if(dsc->src == NULL) {
LV_LOG_WARN("Image draw: src is NULL");
return;
}
if(dsc->opa <= LV_OPA_MIN) return;
LV_PROFILER_BEGIN;
lv_draw_image_dsc_t * new_image_dsc = lv_malloc(sizeof(*dsc));
lv_memcpy(new_image_dsc, dsc, sizeof(*dsc));
lv_result_t res = lv_image_decoder_get_info(new_image_dsc->src, &new_image_dsc->header);
if(res != LV_RESULT_OK) {
LV_LOG_WARN("Couldn't get info about the image");
lv_free(new_image_dsc);
return;
}
lv_draw_task_t * t = lv_draw_add_task(layer, coords);
t->draw_dsc = new_image_dsc;
t->type = LV_DRAW_TASK_TYPE_IMAGE;
lv_draw_finalize_task_creation(layer, t);
LV_PROFILER_END;
}
/**
* Get the type of an image source
* @param src pointer to an image source:
* - pointer to an 'lv_image_t' variable (image stored internally and compiled into the code)
* - a path to a file (e.g. "S:/folder/image.bin")
* - or a symbol (e.g. LV_SYMBOL_CLOSE)
* @return type of the image source LV_IMAGE_SRC_VARIABLE/FILE/SYMBOL/UNKNOWN
*/
lv_image_src_t lv_image_src_get_type(const void * src)
{
lv_image_src_t img_src_type = LV_IMAGE_SRC_UNKNOWN;
if(src == NULL) return img_src_type;
const uint8_t * u8_p = src;
/*The first byte shows the type of the image source*/
if(u8_p[0] >= 0x20 && u8_p[0] <= 0x7F) {
img_src_type = LV_IMAGE_SRC_FILE; /*If it's an ASCII character then it's file name*/
}
else if(u8_p[0] >= 0x80) {
img_src_type = LV_IMAGE_SRC_SYMBOL; /*Symbols begins after 0x7F*/
}
else {
img_src_type = LV_IMAGE_SRC_VARIABLE; /*`lv_image_dsc_t` is draw to the first byte < 0x20*/
}
if(LV_IMAGE_SRC_UNKNOWN == img_src_type) {
LV_LOG_WARN("unknown image type");
}
return img_src_type;
}
/**********************
* STATIC FUNCTIONS
**********************/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_line.c | /**
* @file lv_draw_line.c
*
*/
/*********************
* INCLUDES
*********************/
#include <stdbool.h>
#include "../core/lv_refr.h"
#include "../misc/lv_math.h"
#include "../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
LV_ATTRIBUTE_FAST_MEM void lv_draw_line_dsc_init(lv_draw_line_dsc_t * dsc)
{
lv_memzero(dsc, sizeof(lv_draw_line_dsc_t));
dsc->width = 1;
dsc->opa = LV_OPA_COVER;
dsc->color = lv_color_black();
}
LV_ATTRIBUTE_FAST_MEM void lv_draw_line(struct _lv_layer_t * layer, const lv_draw_line_dsc_t * dsc)
{
LV_PROFILER_BEGIN;
lv_area_t a;
a.x1 = (int32_t)LV_MIN(dsc->p1_x, dsc->p2_x) - dsc->width;
a.x2 = (int32_t)LV_MAX(dsc->p1_x, dsc->p2_x) + dsc->width;
a.y1 = (int32_t)LV_MIN(dsc->p1_y, dsc->p2_y) - dsc->width;
a.y2 = (int32_t)LV_MAX(dsc->p1_y, dsc->p2_y) + dsc->width;
lv_draw_task_t * t = lv_draw_add_task(layer, &a);
t->draw_dsc = lv_malloc(sizeof(*dsc));
lv_memcpy(t->draw_dsc, dsc, sizeof(*dsc));
t->type = LV_DRAW_TASK_TYPE_LINE;
lv_draw_finalize_task_creation(layer, t);
LV_PROFILER_END;
}
/**********************
* STATIC FUNCTIONS
**********************/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_buf.c | /**
* @file lv_draw_buf.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../misc/lv_types.h"
#include "lv_draw_buf.h"
#include "../stdlib/lv_string.h"
#include "../core/lv_global.h"
/*********************
* DEFINES
*********************/
#define handlers LV_GLOBAL_DEFAULT()->draw_buf_handlers
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void * buf_malloc(size_t size, lv_color_format_t color_format);
static void buf_free(void * buf);
static void * buf_align(void * buf, lv_color_format_t color_format);
static uint32_t width_to_stride(uint32_t w, lv_color_format_t color_format);
static void * buf_go_to_xy(const void * buf, uint32_t stride, lv_color_format_t color_format, int32_t x,
int32_t y);
static void buf_clear(void * buf, uint32_t w, uint32_t h, lv_color_format_t color_format, const lv_area_t * a);
static void buf_copy(void * dest_buf, uint32_t dest_w, uint32_t dest_h, const lv_area_t * dest_area_to_copy,
void * src_buf, uint32_t src_w, uint32_t src_h, const lv_area_t * src_area_to_copy,
lv_color_format_t color_format);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void _lv_draw_buf_init_handlers(void)
{
lv_memzero(&handlers, sizeof(lv_draw_buf_handlers_t));
handlers.buf_malloc_cb = buf_malloc;
handlers.buf_free_cb = buf_free;
handlers.align_pointer_cb = buf_align;
handlers.invalidate_cache_cb = NULL;
handlers.width_to_stride_cb = width_to_stride;
handlers.go_to_xy_cb = buf_go_to_xy;
handlers.buf_clear_cb = buf_clear;
handlers.buf_copy_cb = buf_copy;
}
lv_draw_buf_handlers_t * lv_draw_buf_get_handlers(void)
{
return &handlers;
}
uint32_t lv_draw_buf_width_to_stride(uint32_t w, lv_color_format_t color_format)
{
if(handlers.width_to_stride_cb) return handlers.width_to_stride_cb(w, color_format);
else return 0;
}
void * lv_draw_buf_malloc(size_t size_bytes, lv_color_format_t color_format)
{
if(handlers.buf_malloc_cb) return handlers.buf_malloc_cb(size_bytes, color_format);
else return NULL;
}
void lv_draw_buf_free(void * buf)
{
if(handlers.buf_free_cb) handlers.buf_free_cb(buf);
}
void * lv_draw_buf_align(void * data, lv_color_format_t color_format)
{
if(handlers.align_pointer_cb) return handlers.align_pointer_cb(data, color_format);
else return NULL;
}
void lv_draw_buf_invalidate_cache(void * buf, uint32_t stride, lv_color_format_t color_format, const lv_area_t * area)
{
if(handlers.invalidate_cache_cb) handlers.invalidate_cache_cb(buf, stride, color_format, area);
}
void * lv_draw_buf_go_to_xy(const void * buf, uint32_t stride, lv_color_format_t color_format, int32_t x,
int32_t y)
{
if(handlers.go_to_xy_cb) return handlers.go_to_xy_cb(buf, stride, color_format, x, y);
else return NULL;
}
void lv_draw_buf_clear(void * buf, uint32_t w, uint32_t h, lv_color_format_t color_format, const lv_area_t * a)
{
if(handlers.buf_clear_cb) handlers.buf_clear_cb(buf, w, h, color_format, a);
}
void lv_draw_buf_copy(void * dest_buf, uint32_t dest_w, uint32_t dest_h, const lv_area_t * dest_area_to_copy,
void * src_buf, uint32_t src_w, uint32_t src_h, const lv_area_t * src_area_to_copy,
lv_color_format_t color_format)
{
if(handlers.buf_copy_cb) handlers.buf_copy_cb(dest_buf, dest_w, dest_h, dest_area_to_copy,
src_buf, src_w, src_h, src_area_to_copy,
color_format);
}
/**********************
* STATIC FUNCTIONS
**********************/
static void * buf_malloc(size_t size_bytes, lv_color_format_t color_format)
{
LV_UNUSED(color_format);
/*Allocate larger memory to be sure it can be aligned as needed*/
size_bytes += LV_DRAW_BUF_ALIGN - 1;
return lv_malloc(size_bytes);
}
static void buf_free(void * buf)
{
lv_free(buf);
}
static void * buf_align(void * buf, lv_color_format_t color_format)
{
LV_UNUSED(color_format);
uint8_t * buf_u8 = buf;
if(buf_u8) {
buf_u8 += LV_DRAW_BUF_ALIGN - 1;
buf_u8 = (uint8_t *)((lv_uintptr_t) buf_u8 & ~(LV_DRAW_BUF_ALIGN - 1));
}
return buf_u8;
}
static uint32_t width_to_stride(uint32_t w, lv_color_format_t color_format)
{
uint32_t width_byte;
width_byte = w * lv_color_format_get_bpp(color_format);
width_byte = (width_byte + 7) >> 3; /*Round up*/
return (width_byte + LV_DRAW_BUF_STRIDE_ALIGN - 1) & ~(LV_DRAW_BUF_STRIDE_ALIGN - 1);
}
static void * buf_go_to_xy(const void * buf, uint32_t stride, lv_color_format_t color_format, int32_t x,
int32_t y)
{
const uint8_t * buf_tmp = buf;
buf_tmp += stride * y;
buf_tmp += x * lv_color_format_get_size(color_format);
return (void *)buf_tmp;
}
static void buf_clear(void * buf, uint32_t w, uint32_t h, lv_color_format_t color_format, const lv_area_t * a)
{
LV_UNUSED(h);
uint8_t px_size = lv_color_format_get_size(color_format);
uint32_t stride = lv_draw_buf_width_to_stride(w, color_format);
uint8_t * bufc = buf;
/*Got the first pixel of each buffer*/
bufc += stride * a->y1;
bufc += a->x1 * px_size;
uint32_t line_length = lv_area_get_width(a) * px_size;
int32_t y;
for(y = a->y1; y <= a->y2; y++) {
lv_memzero(bufc, line_length);
bufc += stride;
}
}
static void buf_copy(void * dest_buf, uint32_t dest_w, uint32_t dest_h, const lv_area_t * dest_area_to_copy,
void * src_buf, uint32_t src_w, uint32_t src_h, const lv_area_t * src_area_to_copy,
lv_color_format_t color_format)
{
LV_UNUSED(dest_h);
LV_UNUSED(src_h);
uint8_t px_size = lv_color_format_get_size(color_format);
uint8_t * dest_bufc = dest_buf;
uint8_t * src_bufc = src_buf;
uint32_t dest_stride = lv_draw_buf_width_to_stride(dest_w, color_format);
uint32_t src_stride = lv_draw_buf_width_to_stride(src_w, color_format);
/*Got the first pixel of each buffer*/
dest_bufc += dest_stride * dest_area_to_copy->y1;
dest_bufc += dest_area_to_copy->x1 * px_size;
src_bufc += src_stride * src_area_to_copy->y1;
src_bufc += src_area_to_copy->x1 * px_size;
uint32_t line_length = lv_area_get_width(dest_area_to_copy) * px_size;
int32_t y;
for(y = dest_area_to_copy->y1; y <= dest_area_to_copy->y2; y++) {
lv_memcpy(dest_bufc, src_bufc, line_length);
dest_bufc += dest_stride;
src_bufc += src_stride;
}
}
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_label.c | /**
* @file lv_draw_label.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../core/lv_obj.h"
#include "lv_draw_label.h"
#include "../misc/lv_math.h"
#include "../core/lv_obj_event.h"
#include "../misc/lv_bidi.h"
#include "../misc/lv_assert.h"
#include "../stdlib/lv_mem.h"
#include "../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
#define LABEL_RECOLOR_PAR_LENGTH 6
#define LV_LABEL_HINT_UPDATE_TH 1024 /*Update the "hint" if the label's y coordinates have changed more then this*/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void draw_letter(lv_draw_unit_t * draw_unit, lv_draw_glyph_dsc_t * dsc, const lv_point_t * pos,
const lv_font_t * font, uint32_t letter, lv_draw_letter_cb_t cb);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* GLOBAL VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_label_dsc_init(lv_draw_label_dsc_t * dsc)
{
lv_memzero(dsc, sizeof(lv_draw_label_dsc_t));
dsc->opa = LV_OPA_COVER;
dsc->color = lv_color_black();
dsc->font = LV_FONT_DEFAULT;
dsc->sel_start = LV_DRAW_LABEL_NO_TXT_SEL;
dsc->sel_end = LV_DRAW_LABEL_NO_TXT_SEL;
dsc->sel_color = lv_color_black();
dsc->sel_bg_color = lv_palette_main(LV_PALETTE_BLUE);
dsc->bidi_dir = LV_BASE_DIR_LTR;
}
void lv_draw_letter_dsc_init(lv_draw_glyph_dsc_t * dsc)
{
lv_memzero(dsc, sizeof(lv_draw_glyph_dsc_t));
}
LV_ATTRIBUTE_FAST_MEM void lv_draw_label(lv_layer_t * layer, const lv_draw_label_dsc_t * dsc,
const lv_area_t * coords)
{
if(dsc->opa <= LV_OPA_MIN) return;
if(dsc->text == NULL || dsc->text[0] == '\0') return;
if(dsc->font == NULL) {
LV_LOG_WARN("dsc->font == NULL");
return;
}
lv_draw_task_t * t = lv_draw_add_task(layer, coords);
t->draw_dsc = lv_malloc(sizeof(*dsc));
lv_memcpy(t->draw_dsc, dsc, sizeof(*dsc));
t->type = LV_DRAW_TASK_TYPE_LABEL;
/*The text is stored in a local variable so malloc memory for it*/
if(dsc->text_local) {
lv_draw_label_dsc_t * new_dsc = t->draw_dsc;
new_dsc->text = lv_strdup(dsc->text);
}
lv_draw_finalize_task_creation(layer, t);
}
LV_ATTRIBUTE_FAST_MEM void lv_draw_letter(lv_layer_t * layer, lv_draw_label_dsc_t * dsc,
const lv_point_t * point, uint32_t unicode_letter)
{
if(dsc->opa <= LV_OPA_MIN) return;
if(dsc->font == NULL) {
LV_LOG_WARN("dsc->font == NULL");
return;
}
lv_font_glyph_dsc_t g;
lv_font_get_glyph_dsc(dsc->font, &g, unicode_letter, 0);
lv_area_t a;
a.x1 = point->x;
a.y1 = point->y;
a.x2 = a.x1 + g.adv_w;
a.y2 = a.y1 + lv_font_get_line_height(g.resolved_font ? g.resolved_font : dsc->font);
/*lv_draw_label needs UTF8 text so convert the Unicode character to an UTF8 string */
uint32_t letter_buf[2];
letter_buf[0] = _lv_text_unicode_to_encoded(unicode_letter);
letter_buf[1] = '\0';
const char * letter_buf_char = (const char *)letter_buf;
#if LV_BIG_ENDIAN_SYSTEM
while(*letter_buf_char == 0) ++letter_buf_char;
#endif
dsc->text = letter_buf_char;
dsc->text_local = 1;
lv_draw_label(layer, dsc, &a);
}
void lv_draw_label_iterate_letters(lv_draw_unit_t * draw_unit, const lv_draw_label_dsc_t * dsc,
const lv_area_t * coords,
lv_draw_letter_cb_t cb)
{
const lv_font_t * font = dsc->font;
int32_t w;
lv_area_t clipped_area;
bool clip_ok = _lv_area_intersect(&clipped_area, coords, draw_unit->clip_area);
if(!clip_ok) return;
lv_text_align_t align = dsc->align;
lv_base_dir_t base_dir = dsc->bidi_dir;
lv_bidi_calculate_align(&align, &base_dir, dsc->text);
if((dsc->flag & LV_TEXT_FLAG_EXPAND) == 0) {
/*Normally use the label's width as width*/
w = lv_area_get_width(coords);
}
else {
/*If EXPAND is enabled then not limit the text's width to the object's width*/
lv_point_t p;
lv_text_get_size(&p, dsc->text, dsc->font, dsc->letter_space, dsc->line_space, LV_COORD_MAX,
dsc->flag);
w = p.x;
}
int32_t line_height_font = lv_font_get_line_height(font);
int32_t line_height = line_height_font + dsc->line_space;
/*Init variables for the first line*/
int32_t line_width = 0;
lv_point_t pos;
pos.x = coords->x1;
pos.y = coords->y1;
int32_t x_ofs = 0;
int32_t y_ofs = 0;
x_ofs = dsc->ofs_x;
y_ofs = dsc->ofs_y;
pos.y += y_ofs;
uint32_t line_start = 0;
int32_t last_line_start = -1;
/*Check the hint to use the cached info*/
if(dsc->hint && y_ofs == 0 && coords->y1 < 0) {
/*If the label changed too much recalculate the hint.*/
if(LV_ABS(dsc->hint->coord_y - coords->y1) > LV_LABEL_HINT_UPDATE_TH - 2 * line_height) {
dsc->hint->line_start = -1;
}
last_line_start = dsc->hint->line_start;
}
/*Use the hint if it's valid*/
if(dsc->hint && last_line_start >= 0) {
line_start = last_line_start;
pos.y += dsc->hint->y;
}
uint32_t line_end = line_start + _lv_text_get_next_line(&dsc->text[line_start], font, dsc->letter_space, w, NULL,
dsc->flag);
/*Go the first visible line*/
while(pos.y + line_height_font < draw_unit->clip_area->y1) {
/*Go to next line*/
line_start = line_end;
line_end += _lv_text_get_next_line(&dsc->text[line_start], font, dsc->letter_space, w, NULL, dsc->flag);
pos.y += line_height;
/*Save at the threshold coordinate*/
if(dsc->hint && pos.y >= -LV_LABEL_HINT_UPDATE_TH && dsc->hint->line_start < 0) {
dsc->hint->line_start = line_start;
dsc->hint->y = pos.y - coords->y1;
dsc->hint->coord_y = coords->y1;
}
if(dsc->text[line_start] == '\0') return;
}
/*Align to middle*/
if(align == LV_TEXT_ALIGN_CENTER) {
line_width = lv_text_get_width(&dsc->text[line_start], line_end - line_start, font, dsc->letter_space);
pos.x += (lv_area_get_width(coords) - line_width) / 2;
}
/*Align to the right*/
else if(align == LV_TEXT_ALIGN_RIGHT) {
line_width = lv_text_get_width(&dsc->text[line_start], line_end - line_start, font, dsc->letter_space);
pos.x += lv_area_get_width(coords) - line_width;
}
uint32_t sel_start = dsc->sel_start;
uint32_t sel_end = dsc->sel_end;
if(sel_start > sel_end) {
uint32_t tmp = sel_start;
sel_start = sel_end;
sel_end = tmp;
}
lv_area_t bg_coords;
lv_draw_glyph_dsc_t draw_letter_dsc;
lv_draw_letter_dsc_init(&draw_letter_dsc);
draw_letter_dsc.opa = dsc->opa;
draw_letter_dsc.bg_coords = &bg_coords;
draw_letter_dsc.color = dsc->color;
lv_draw_fill_dsc_t fill_dsc;
lv_draw_fill_dsc_init(&fill_dsc);
fill_dsc.opa = dsc->opa;
int32_t underline_width = font->underline_thickness ? font->underline_thickness : 1;
int32_t line_start_x;
uint32_t i;
int32_t letter_w;
/*Write out all lines*/
while(dsc->text[line_start] != '\0') {
pos.x += x_ofs;
line_start_x = pos.x;
/*Write all letter of a line*/
i = 0;
#if LV_USE_BIDI
char * bidi_txt = lv_malloc(line_end - line_start + 1);
LV_ASSERT_MALLOC(bidi_txt);
_lv_bidi_process_paragraph(dsc->text + line_start, bidi_txt, line_end - line_start, base_dir, NULL, 0);
#else
const char * bidi_txt = dsc->text + line_start;
#endif
while(i < line_end - line_start) {
uint32_t logical_char_pos = 0;
if(sel_start != 0xFFFF && sel_end != 0xFFFF) {
#if LV_USE_BIDI
logical_char_pos = _lv_text_encoded_get_char_id(dsc->text, line_start);
uint32_t t = _lv_text_encoded_get_char_id(bidi_txt, i);
logical_char_pos += _lv_bidi_get_logical_pos(bidi_txt, NULL, line_end - line_start, base_dir, t, NULL);
#else
logical_char_pos = _lv_text_encoded_get_char_id(dsc->text, line_start + i);
#endif
}
uint32_t letter;
uint32_t letter_next;
_lv_text_encoded_letter_next_2(bidi_txt, &letter, &letter_next, &i);
letter_w = lv_font_get_glyph_width(font, letter, letter_next);
/*Always set the bg_coordinates for placeholder drawing*/
bg_coords.x1 = pos.x;
bg_coords.y1 = pos.y;
bg_coords.x2 = pos.x + letter_w + dsc->letter_space - 1;
bg_coords.y2 = pos.y + line_height - 1;
if(i >= line_end - line_start) {
if(dsc->decor & LV_TEXT_DECOR_UNDERLINE) {
lv_area_t fill_area;
fill_area.x1 = line_start_x;
fill_area.x2 = pos.x + letter_w - 1;
fill_area.y1 = pos.y + font->line_height - font->base_line - font->underline_position;
fill_area.y2 = fill_area.y1 + underline_width - 1;
fill_dsc.color = dsc->color;
cb(draw_unit, NULL, &fill_dsc, &fill_area);
}
if(dsc->decor & LV_TEXT_DECOR_STRIKETHROUGH) {
lv_area_t fill_area;
fill_area.x1 = line_start_x;
fill_area.x2 = pos.x + letter_w - 1;
fill_area.y1 = pos.y + (font->line_height - font->base_line) * 2 / 3 + font->underline_thickness / 2;
fill_area.y2 = fill_area.y1 + underline_width - 1;
fill_dsc.color = dsc->color;
cb(draw_unit, NULL, &fill_dsc, &fill_area);
}
}
if(sel_start != 0xFFFF && sel_end != 0xFFFF && logical_char_pos >= sel_start && logical_char_pos < sel_end) {
draw_letter_dsc.color = dsc->sel_color;
fill_dsc.color = dsc->sel_bg_color;
cb(draw_unit, NULL, &fill_dsc, &bg_coords);
}
else {
draw_letter_dsc.color = dsc->color;
}
draw_letter(draw_unit, &draw_letter_dsc, &pos, font, letter, cb);
if(letter_w > 0) {
pos.x += letter_w + dsc->letter_space;
}
}
#if LV_USE_BIDI
lv_free(bidi_txt);
bidi_txt = NULL;
#endif
/*Go to next line*/
line_start = line_end;
line_end += _lv_text_get_next_line(&dsc->text[line_start], font, dsc->letter_space, w, NULL, dsc->flag);
pos.x = coords->x1;
/*Align to middle*/
if(align == LV_TEXT_ALIGN_CENTER) {
line_width =
lv_text_get_width(&dsc->text[line_start], line_end - line_start, font, dsc->letter_space);
pos.x += (lv_area_get_width(coords) - line_width) / 2;
}
/*Align to the right*/
else if(align == LV_TEXT_ALIGN_RIGHT) {
line_width =
lv_text_get_width(&dsc->text[line_start], line_end - line_start, font, dsc->letter_space);
pos.x += lv_area_get_width(coords) - line_width;
}
/*Go the next line position*/
pos.y += line_height;
if(pos.y > draw_unit->clip_area->y2) break;
}
lv_draw_buf_free(draw_letter_dsc._bitmap_buf_unaligned);
LV_ASSERT_MEM_INTEGRITY();
}
/**********************
* STATIC FUNCTIONS
**********************/
static void draw_letter(lv_draw_unit_t * draw_unit, lv_draw_glyph_dsc_t * dsc, const lv_point_t * pos,
const lv_font_t * font, uint32_t letter, lv_draw_letter_cb_t cb)
{
lv_font_glyph_dsc_t g;
LV_PROFILER_BEGIN;
bool g_ret = lv_font_get_glyph_dsc(font, &g, letter, '\0');
if(g_ret == false) {
/*Add warning if the dsc is not found
*but do not print warning for non printable ASCII chars (e.g. '\n')*/
if(letter >= 0x20 &&
letter != 0xf8ff && /*LV_SYMBOL_DUMMY*/
letter != 0x200c) { /*ZERO WIDTH NON-JOINER*/
LV_LOG_WARN("lv_draw_letter: glyph dsc. not found for U+%" LV_PRIX32, letter);
}
}
/*Don't draw anything if the character is empty. E.g. space*/
if((g.box_h == 0) || (g.box_w == 0)) {
LV_PROFILER_END;
return;
}
lv_area_t letter_coords;
letter_coords.x1 = pos->x + g.ofs_x;
letter_coords.x2 = letter_coords.x1 + g.box_w - 1;
letter_coords.y1 = pos->y + (font->line_height - font->base_line) - g.box_h - g.ofs_y;
letter_coords.y2 = letter_coords.y1 + g.box_h - 1;
/*If the letter is completely out of mask don't draw it*/
if(_lv_area_is_out(&letter_coords, draw_unit->clip_area, 0)) {
LV_PROFILER_END;
return;
}
uint32_t bitmap_size = lv_draw_buf_width_to_stride(g.box_w, LV_COLOR_FORMAT_A8) * g.box_h;
bitmap_size = (bitmap_size + 63) &
(~63); /*Round up to avoid many allocations if the next buffer is just slightly larger*/
if(dsc->_bitmap_buf_size < bitmap_size) {
lv_draw_buf_free(dsc->_bitmap_buf_unaligned);
dsc->_bitmap_buf_unaligned = lv_draw_buf_malloc(bitmap_size, LV_COLOR_FORMAT_A8);
LV_ASSERT_MALLOC(dsc->_bitmap_buf_unaligned);
dsc->bitmap_buf = lv_draw_buf_align(dsc->_bitmap_buf_unaligned, LV_COLOR_FORMAT_A8);
dsc->_bitmap_buf_size = bitmap_size;
}
if(g.resolved_font) {
dsc->bitmap = lv_font_get_glyph_bitmap(g.resolved_font, letter, dsc->bitmap_buf);
}
else {
dsc->bitmap = NULL;
}
dsc->letter_coords = &letter_coords;
if(g.bpp == LV_IMGFONT_BPP) dsc->format = LV_DRAW_LETTER_BITMAP_FORMAT_IMAGE;
else dsc->format = LV_DRAW_LETTER_BITMAP_FORMAT_A8;
cb(draw_unit, dsc, NULL, NULL);
LV_PROFILER_END;
}
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_buf.h | /**
* @file lv_draw_buf.h
*
*/
#ifndef LV_DRAW_BUF_H
#define LV_DRAW_BUF_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../misc/lv_area.h"
#include "../misc/lv_color.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef void * (*lv_draw_buf_malloc_cb)(size_t size, lv_color_format_t color_format);
typedef void (*lv_draw_buf_free_cb)(void * draw_buf);
typedef void * (*lv_draw_buf_align_cb)(void * buf, lv_color_format_t color_format);
typedef void (*lv_draw_buf_invalidate_cache_cb)(void * buf, uint32_t stride, lv_color_format_t color_format,
const lv_area_t * area);
typedef uint32_t (*lv_draw_buf_width_to_stride_cb)(uint32_t w, lv_color_format_t color_format);
typedef void * (*lv_draw_buf_go_to_xy_cb)(const void * buf, uint32_t stride, lv_color_format_t color_format,
int32_t x, int32_t y);
typedef void (*lv_draw_buf_clear_cb)(void * buf, uint32_t w, uint32_t h, lv_color_format_t color_format,
const lv_area_t * a);
typedef void (*lv_draw_buf_copy_cb)(void * dest_buf, uint32_t dest_w, uint32_t dest_h,
const lv_area_t * dest_area_to_copy,
void * src_buf, uint32_t src_w, uint32_t src_h, const lv_area_t * src_area_to_copy,
lv_color_format_t color_format);
typedef struct {
lv_draw_buf_malloc_cb buf_malloc_cb;
lv_draw_buf_free_cb buf_free_cb;
lv_draw_buf_align_cb align_pointer_cb;
lv_draw_buf_invalidate_cache_cb invalidate_cache_cb;
lv_draw_buf_width_to_stride_cb width_to_stride_cb;
lv_draw_buf_go_to_xy_cb go_to_xy_cb;
lv_draw_buf_clear_cb buf_clear_cb;
lv_draw_buf_copy_cb buf_copy_cb;
} lv_draw_buf_handlers_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Called internally to initialize the draw_buf_handlers in lv_global
*/
void _lv_draw_buf_init_handlers(void);
/**
* Get the struct which holds the callbacks for draw buf management.
* Custom callback can be set on the returned value
* @return pointer to the struct of handlers
*/
lv_draw_buf_handlers_t * lv_draw_buf_get_handlers(void);
/**
* Allocate a buffer with the given size. It might allocate slightly larger buffer to fulfill the alignment requirements.
* @param size the size to allocate in bytes
* @param color_format the color format of the buffer to allocate
* @return the allocated buffer.
* @note The returned value can be saved in draw_buf->buf
* @note lv_draw_buf_align can be sued the align the returned pointer
*/
void * lv_draw_buf_malloc(size_t size_bytes, lv_color_format_t color_format);
/**
* Free a buffer allocated by lv_draw_buf_malloc
* @param buf pointer to a buffer
*/
void lv_draw_buf_free(void * buf);
/**
* Align the address of a buffer. The buffer needs to be large enough for the real data after alignment
* @param buf the data to align
* @param color_format the color format of the buffer
* @return the aligned buffer
*/
void * lv_draw_buf_align(void * buf, lv_color_format_t color_format);
/**
* Invalidate the cache of the buffer
* @param buf a memory address to invalidate
* @param stride stride of the buffer
* @param color_format color format of the buffer
* @param area the area to invalidate in the buffer
*/
void lv_draw_buf_invalidate_cache(void * buf, uint32_t stride, lv_color_format_t color_format, const lv_area_t * area);
/**
* Calculate the stride in bytes based on a width and color format
* @param w the width in pixels
* @param color_format the color format
* @return the stride in bytes
*/
uint32_t lv_draw_buf_width_to_stride(uint32_t w, lv_color_format_t color_format);
/**
* Got to a pixel at X and Y coordinate in a buffer
* @param buf pointer to a buffer
* @param stride stride of the buffer
* @param color_format color format of the buffer
* @param x the target X coordinate
* @param y the target X coordinate
* @return `buf` offset to point to the given X and Y coordinate
*/
void * lv_draw_buf_go_to_xy(const void * buf, uint32_t stride, lv_color_format_t color_format, int32_t x,
int32_t y);
/**
* Clear an area on the buffer
* @param draw_buf pointer to draw buffer
* @param w width of the buffer
* @param h height of the buffer
* @param color_format color format of the buffer
* @param a the area to clear, or NULL to clear the whole buffer
*/
void lv_draw_buf_clear(void * buf, uint32_t w, uint32_t h, lv_color_format_t color_format, const lv_area_t * a);
/**
* Copy an area from a buffer to an other
* @param dest_buf pointer to the destination buffer)
* @param dest_w width of the destination buffer in pixels
* @param dest_h height of the destination buffer in pixels
* @param dest_area_to_copy the area to copy from the destination buffer
* @param src_buf pointer to the source buffer
* @param src_w width of the source buffer in pixels
* @param src_h height of the source buffer in pixels
* @param src_area_to_copy the area to copy from the destination buffer
* @param color_format the color format, should be the same for both buffers
* @note `dest_area_to_copy` and `src_area_to_copy` should have the same width and height
*/
void lv_draw_buf_copy(void * dest_buf, uint32_t dest_w, uint32_t dest_h, const lv_area_t * dest_area_to_copy,
void * src_buf, uint32_t src_w, uint32_t src_h, const lv_area_t * src_area_to_copy,
lv_color_format_t color_format);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_BUF_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_image_decoder.h | /**
* @file lv_image_decoder.h
*
*/
#ifndef LV_IMAGE_DECODER_H
#define LV_IMAGE_DECODER_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#include <stdint.h>
#include "lv_image_buf.h"
#include "../misc/lv_fs.h"
#include "../misc/lv_types.h"
#include "../misc/lv_area.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**
* Source of image.*/
enum _lv_image_src_t {
LV_IMAGE_SRC_VARIABLE, /** Binary/C variable*/
LV_IMAGE_SRC_FILE, /** File in filesystem*/
LV_IMAGE_SRC_SYMBOL, /** Symbol (@ref lv_symbol_def.h)*/
LV_IMAGE_SRC_UNKNOWN, /** Unknown source*/
};
#ifdef DOXYGEN
typedef _lv_image_src_t lv_image_src_t;
#else
typedef uint8_t lv_image_src_t;
#endif /*DOXYGEN*/
/*Decoder function definitions*/
struct _lv_image_decoder_dsc_t;
struct _lv_image_decoder_t;
struct _lv_cache_entry_t;
/**
* Get info from an image and store in the `header`
* @param src the image source. Can be a pointer to a C array or a file name (Use
* `lv_image_src_get_type` to determine the type)
* @param header store the info here
* @return LV_RESULT_OK: info written correctly; LV_RESULT_INVALID: failed
*/
typedef lv_result_t (*lv_image_decoder_info_f_t)(struct _lv_image_decoder_t * decoder, const void * src,
lv_image_header_t * header);
/**
* Open an image for decoding. Prepare it as it is required to read it later
* @param decoder pointer to the decoder the function associated with
* @param dsc pointer to decoder descriptor. `src`, `color` are already initialized in it.
*/
typedef lv_result_t (*lv_image_decoder_open_f_t)(struct _lv_image_decoder_t * decoder,
struct _lv_image_decoder_dsc_t * dsc);
/**
* Decode `len` pixels starting from the given `x`, `y` coordinates and store them in `buf`.
* Required only if the "open" function can't return with the whole decoded pixel array.
* @param decoder pointer to the decoder the function associated with
* @param dsc pointer to decoder descriptor
* @param x start x coordinate
* @param y start y coordinate
* @param len number of pixels to decode
* @param buf a buffer to store the decoded pixels
* @return LV_RESULT_OK: ok; LV_RESULT_INVALID: failed
*/
typedef lv_result_t (*lv_image_decoder_get_area_cb_t)(struct _lv_image_decoder_t * decoder,
struct _lv_image_decoder_dsc_t * dsc,
const lv_area_t * full_area, lv_area_t * decoded_area);
/**
* Close the pending decoding. Free resources etc.
* @param decoder pointer to the decoder the function associated with
* @param dsc pointer to decoder descriptor
*/
typedef void (*lv_image_decoder_close_f_t)(struct _lv_image_decoder_t * decoder, struct _lv_image_decoder_dsc_t * dsc);
typedef struct _lv_image_decoder_t {
lv_image_decoder_info_f_t info_cb;
lv_image_decoder_open_f_t open_cb;
lv_image_decoder_get_area_cb_t get_area_cb;
lv_image_decoder_close_f_t close_cb;
void * user_data;
} lv_image_decoder_t;
/**Describe an image decoding session. Stores data about the decoding*/
typedef struct _lv_image_decoder_dsc_t {
/**The decoder which was able to open the image source*/
lv_image_decoder_t * decoder;
/**The image source. A file path like "S:my_img.png" or pointer to an `lv_image_dsc_t` variable*/
const void * src;
/**Frame of the image, using with animated images*/
int32_t frame_id;
/**Type of the source: file or variable. Can be set in `open` function if required*/
lv_image_src_t src_type;
/**Info about the opened image: color format, size, etc. MUST be set in `open` function*/
lv_image_header_t header;
/** Pointer to a buffer where the image's data (pixels) are stored in a decoded, plain format.
* MUST be set in `open` function*/
const uint8_t * img_data;
const lv_color32_t * palette;
uint32_t palette_size;
/** How much time did it take to open the image. [ms]
* If not set `lv_image_cache` will measure and set the time to open*/
uint32_t time_to_open;
/**A text to display instead of the image when the image can't be opened.
* Can be set in `open` function or set NULL.*/
const char * error_msg;
/**Point to cache entry information*/
struct _lv_cache_entry_t * cache_entry;
/**Store any custom data here is required*/
void * user_data;
} lv_image_decoder_dsc_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Initialize the image decoder module
*/
void _lv_image_decoder_init(void);
/**
* Get information about an image.
* Try the created image decoder one by one. Once one is able to get info that info will be used.
* @param src the image source. Can be
* 1) File name: E.g. "S:folder/img1.png" (The drivers needs to registered via `lv_fs_drv_register()`)
* 2) Variable: Pointer to an `lv_image_dsc_t` variable
* 3) Symbol: E.g. `LV_SYMBOL_OK`
* @param header the image info will be stored here
* @return LV_RESULT_OK: success; LV_RESULT_INVALID: wasn't able to get info about the image
*/
lv_result_t lv_image_decoder_get_info(const void * src, lv_image_header_t * header);
/**
* Open an image.
* Try the created image decoders one by one. Once one is able to open the image that decoder is saved in `dsc`
* @param dsc describes a decoding session. Simply a pointer to an `lv_image_decoder_dsc_t` variable.
* @param src the image source. Can be
* 1) File name: E.g. "S:folder/img1.png" (The drivers needs to registered via `lv_fs_drv_register())`)
* 2) Variable: Pointer to an `lv_image_dsc_t` variable
* 3) Symbol: E.g. `LV_SYMBOL_OK`
* @param color The color of the image with `LV_IMAGE_CF_ALPHA_...`
* @param frame_id the index of the frame. Used only with animated images, set 0 for normal images
* @return LV_RESULT_OK: opened the image. `dsc->img_data` and `dsc->header` are set.
* LV_RESULT_INVALID: none of the registered image decoders were able to open the image.
*/
lv_result_t lv_image_decoder_open(lv_image_decoder_dsc_t * dsc, const void * src, lv_color_t color, int32_t frame_id);
/**
* Decode an area of the opened image
* @param dsc image decoder descriptor
* @param full_area start X coordinate (from left)
* @param decoded_area start Y coordinate (from top)
* @return LV_RESULT_OK: success; LV_RESULT_INVALID: an error occurred
*/
lv_result_t lv_image_decoder_get_area(lv_image_decoder_dsc_t * dsc, const lv_area_t * full_area,
lv_area_t * decoded_area);
/**
* Close a decoding session
* @param dsc pointer to `lv_image_decoder_dsc_t` used in `lv_image_decoder_open`
*/
void lv_image_decoder_close(lv_image_decoder_dsc_t * dsc);
/**
* Create a new image decoder
* @return pointer to the new image decoder
*/
lv_image_decoder_t * lv_image_decoder_create(void);
/**
* Delete an image decoder
* @param decoder pointer to an image decoder
*/
void lv_image_decoder_delete(lv_image_decoder_t * decoder);
/**
* Get the next image decoder in the linked list of image decoders
* @param decoder pointer to an image decoder or NULL to get the first one
* @return the next image decoder or NULL if no more image decoder exists
*/
lv_image_decoder_t * lv_image_decoder_get_next(lv_image_decoder_t * decoder);
/**
* Set a callback to get information about the image
* @param decoder pointer to an image decoder
* @param info_cb a function to collect info about an image (fill an `lv_image_header_t` struct)
*/
void lv_image_decoder_set_info_cb(lv_image_decoder_t * decoder, lv_image_decoder_info_f_t info_cb);
/**
* Set a callback to open an image
* @param decoder pointer to an image decoder
* @param open_cb a function to open an image
*/
void lv_image_decoder_set_open_cb(lv_image_decoder_t * decoder, lv_image_decoder_open_f_t open_cb);
/**
* Set a callback to a decoded line of an image
* @param decoder pointer to an image decoder
* @param read_line_cb a function to read a line of an image
*/
void lv_image_decoder_set_get_area_cb(lv_image_decoder_t * decoder, lv_image_decoder_get_area_cb_t read_line_cb);
/**
* Set a callback to close a decoding session. E.g. close files and free other resources.
* @param decoder pointer to an image decoder
* @param close_cb a function to close a decoding session
*/
void lv_image_decoder_set_close_cb(lv_image_decoder_t * decoder, lv_image_decoder_close_f_t close_cb);
/**
* Get info about a built-in image
* @param decoder the decoder where this function belongs
* @param src the image source: pointer to an `lv_image_dsc_t` variable, a file path or a symbol
* @param header store the image data here
* @return LV_RESULT_OK: the info is successfully stored in `header`; LV_RESULT_INVALID: unknown format or other error.
*/
lv_result_t lv_image_decoder_built_in_info(lv_image_decoder_t * decoder, const void * src, lv_image_header_t * header);
lv_result_t lv_image_decoder_built_in_get_area(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc,
const lv_area_t * full_area, lv_area_t * decoded_area);
/**
* Open a built in image
* @param decoder the decoder where this function belongs
* @param dsc pointer to decoder descriptor. `src`, `style` are already initialized in it.
* @return LV_RESULT_OK: the info is successfully stored in `header`; LV_RESULT_INVALID: unknown format or other error.
*/
lv_result_t lv_image_decoder_built_in_open(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc);
/**
* Close the pending decoding. Free resources etc.
* @param decoder pointer to the decoder the function associated with
* @param dsc pointer to decoder descriptor
*/
void lv_image_decoder_built_in_close(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_IMAGE_DECODER_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_label.h | /**
* @file lv_draw_label.h
*
*/
#ifndef LV_DRAW_LABEL_H
#define LV_DRAW_LABEL_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "lv_draw.h"
#include "../misc/lv_bidi.h"
#include "../misc/lv_text.h"
#include "../misc/lv_color.h"
#include "../misc/lv_style.h"
/*********************
* DEFINES
*********************/
#define LV_DRAW_LABEL_NO_TXT_SEL (0xFFFF)
/**********************
* TYPEDEFS
**********************/
struct _lv_layer_t;
/** Store some info to speed up drawing of very large texts
* It takes a lot of time to get the first visible character because
* all the previous characters needs to be checked to calculate the positions.
* This structure stores an earlier (e.g. at -1000 px) coordinate and the index of that line.
* Therefore the calculations can start from here.*/
typedef struct _lv_draw_label_hint_t {
/** Index of the line at `y` coordinate*/
int32_t line_start;
/** Give the `y` coordinate of the first letter at `line start` index. Relative to the label's coordinates*/
int32_t y;
/** The 'y1' coordinate of the label when the hint was saved.
* Used to invalidate the hint if the label has moved too much.*/
int32_t coord_y;
} lv_draw_label_hint_t;
typedef struct {
lv_draw_dsc_base_t base;
const char * text;
const lv_font_t * font;
uint32_t sel_start;
uint32_t sel_end;
lv_color_t color;
lv_color_t sel_color;
lv_color_t sel_bg_color;
int32_t line_space;
int32_t letter_space;
int32_t ofs_x;
int32_t ofs_y;
lv_opa_t opa;
lv_base_dir_t bidi_dir;
lv_text_align_t align;
lv_text_flag_t flag;
lv_text_decor_t decor : 3;
lv_blend_mode_t blend_mode: 3;
uint8_t text_local :
1; /**< 1: malloc buffer and copy `text` there. 0: `text` is const and it's pointer will be valid during rendering*/
lv_draw_label_hint_t * hint;
} lv_draw_label_dsc_t;
typedef enum {
LV_DRAW_LETTER_BITMAP_FORMAT_A8,
LV_DRAW_LETTER_BITMAP_FORMAT_IMAGE,
} lv_draw_letter_bitmap_format_t;
typedef struct {
const uint8_t * bitmap;
uint8_t * _bitmap_buf_unaligned;
uint8_t * bitmap_buf;
uint32_t _bitmap_buf_size;
lv_draw_letter_bitmap_format_t format;
const lv_area_t * letter_coords;
const lv_area_t * bg_coords;
lv_color_t color;
lv_opa_t opa;
} lv_draw_glyph_dsc_t;
typedef void(*lv_draw_letter_cb_t)(lv_draw_unit_t * draw_unit, lv_draw_glyph_dsc_t * dsc, lv_draw_fill_dsc_t * fill_dsc,
const lv_area_t * fill_area);
void lv_draw_label_iterate_letters(lv_draw_unit_t * draw_unit, const lv_draw_label_dsc_t * dsc,
const lv_area_t * coords,
lv_draw_letter_cb_t cb);
/**********************
* GLOBAL PROTOTYPES
**********************/
LV_ATTRIBUTE_FAST_MEM void lv_draw_label_dsc_init(lv_draw_label_dsc_t * dsc);
void lv_draw_letter_dsc_init(lv_draw_glyph_dsc_t * dsc);
/**
* Write a text
* @param layer pointer to a layer
* @param dsc pointer to draw descriptor
* @param coords coordinates of the label
* It is managed by the draw to speed up the drawing of very long texts (thousands of lines).
*/
LV_ATTRIBUTE_FAST_MEM void lv_draw_label(lv_layer_t * layer, const lv_draw_label_dsc_t * dsc,
const lv_area_t * coords);
/**
* Write a text
* @param layer pointer to a layer
* @param dsc pointer to draw descriptor
* @param point position of the label
* @param unicode_letter the letter to draw
* It is managed by the draw to speed up the drawing of very long texts (thousands of lines).
*/
LV_ATTRIBUTE_FAST_MEM void lv_draw_letter(lv_layer_t * layer, lv_draw_label_dsc_t * dsc,
const lv_point_t * point, uint32_t unicode_letter);
/***********************
* GLOBAL VARIABLES
***********************/
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_LABEL_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_arc.h | /**
* @file lv_draw_arc.h
*
*/
#ifndef LV_DRAW_ARC_H
#define LV_DRAW_ARC_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#include "../misc/lv_color.h"
#include "../misc/lv_area.h"
#include "../misc/lv_style.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_draw_dsc_base_t base;
lv_color_t color;
int32_t width;
lv_value_precise_t start_angle;
lv_value_precise_t end_angle;
lv_point_t center;
uint16_t radius;
const void * img_src;
lv_opa_t opa;
uint8_t rounded : 1;
} lv_draw_arc_dsc_t;
struct _lv_layer_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
void lv_draw_arc_dsc_init(lv_draw_arc_dsc_t * dsc);
void lv_draw_arc(struct _lv_layer_t * layer, const lv_draw_arc_dsc_t * dsc);
/**
* Get an area the should be invalidated when the arcs angle changed between start_angle and end_ange
* @param x the x coordinate of the center of the arc
* @param y the y coordinate of the center of the arc
* @param radius the radius of the arc
* @param start_angle the start angle of the arc (0 deg on the bottom, 90 deg on the right)
* @param end_angle the end angle of the arc
* @param w width of the arc
* @param rounded true: the arc is rounded
* @param area store the area to invalidate here
*/
void lv_draw_arc_get_area(int32_t x, int32_t y, uint16_t radius, lv_value_precise_t start_angle,
lv_value_precise_t end_angle,
int32_t w, bool rounded, lv_area_t * area);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_ARC_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw.h | /**
* @file lv_draw.h
*
*/
#ifndef LV_DRAW_H
#define LV_DRAW_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#include "../misc/lv_style.h"
#include "../misc/lv_text.h"
#include "../misc/lv_profiler.h"
#include "../misc/lv_cache.h"
#include "lv_image_decoder.h"
#include "../osal/lv_os.h"
#include "lv_draw_buf.h"
/*********************
* DEFINES
*********************/
#define LV_DRAW_UNIT_ID_ANY 0
/**********************
* TYPEDEFS
**********************/
struct _lv_draw_image_dsc_t;
struct _lv_display_t;
typedef enum {
LV_DRAW_TASK_TYPE_FILL,
LV_DRAW_TASK_TYPE_BORDER,
LV_DRAW_TASK_TYPE_BOX_SHADOW,
LV_DRAW_TASK_TYPE_BG_IMG,
LV_DRAW_TASK_TYPE_LABEL,
LV_DRAW_TASK_TYPE_IMAGE,
LV_DRAW_TASK_TYPE_LAYER,
LV_DRAW_TASK_TYPE_LINE,
LV_DRAW_TASK_TYPE_ARC,
LV_DRAW_TASK_TYPE_TRIANGLE,
LV_DRAW_TASK_TYPE_MASK_RECTANGLE,
LV_DRAW_TASK_TYPE_MASK_BITMAP,
} lv_draw_task_type_t;
typedef enum {
LV_DRAW_TASK_STATE_WAITING, /*Waiting for something to be finished. E.g. rendering a layer*/
LV_DRAW_TASK_STATE_QUEUED,
LV_DRAW_TASK_STATE_IN_PROGRESS,
LV_DRAW_TASK_STATE_READY,
} lv_draw_task_state_t;
typedef struct _lv_draw_task_t {
struct _lv_draw_task_t * next;
lv_draw_task_type_t type;
/**
* The bounding box of the thing to draw
*/
lv_area_t area;
/** The original area which is updated*/
lv_area_t clip_area_original;
/**
* The clip area of the layer is saved here when the draw task is created.
* As the clip area of the layer can be changed as new draw tasks are added its current value needs to be saved.
* Therefore during drawing the layer's clip area shouldn't be used as it might be already changed for other draw tasks.
*/
lv_area_t clip_area;
volatile int state; /*int instead of lv_draw_task_state_t to be sure its atomic*/
void * draw_dsc;
/**
* The ID of the draw_unit which should take this task
*/
uint8_t preferred_draw_unit_id;
/**
* Set to which extent `preferred_draw_unit_id` is good at this task.
* 80: means 20% better (faster) than software rendering
* 100: the default value
* 110: means 10% better (faster) than software rendering
*/
uint8_t preference_score;
} lv_draw_task_t;
typedef struct {
void * user_data;
} lv_draw_mask_t;
typedef struct _lv_draw_unit_t {
struct _lv_draw_unit_t * next;
/**
* The target_layer on which drawing should happen
*/
struct _lv_layer_t * target_layer;
const lv_area_t * clip_area;
/**
* Called to try to assign a draw task to itself.
* `lv_draw_get_next_available_task` can be used to get an independent draw task.
* A draw task should be assign only if the draw unit can draw it too
* @param draw_unit pointer to the draw unit
* @param layer pointer to a layer on which the draw task should be drawn
* @return >=0: The number of taken draw task
* -1: There where no available draw tasks at all.
* Also means to no call the dispatcher of the other draw units as there is no draw task to take
*/
int32_t (*dispatch_cb)(struct _lv_draw_unit_t * draw_unit, struct _lv_layer_t * layer);
/**
*
* @param draw_unit
* @param task
* @return
*/
int32_t (*evaluate_cb)(struct _lv_draw_unit_t * draw_unit, lv_draw_task_t * task);
} lv_draw_unit_t;
typedef struct _lv_layer_t {
/** The unaligned buffer where drawing will happen*/
void * buf_unaligned;
/** The aligned buffer, result of lv_draw_buf_align(layer->buf_unaligned)*/
void * buf;
uint32_t buf_stride;
lv_area_t buf_area;
lv_color_format_t color_format;
/**
* The current clip area with absolute coordinates, always the same or smaller than `buf_area`
* Can be set before new draw tasks are added to indicate the clip area of the draw tasks.
* Therefore `lv_draw_add_task()` always saves it in the new draw task to know the clip area when the draw task was added.
* During drawing the draw units also sees the saved clip_area and should use it during drawing.
* During drawing the layer's clip area shouldn't be used as it might be already changed for other draw tasks.
*/
lv_area_t clip_area;
/**
* Linked list of draw tasks
*/
lv_draw_task_t * draw_task_head;
struct _lv_layer_t * parent;
struct _lv_layer_t * next;
bool all_tasks_added;
void * user_data;
} lv_layer_t;
typedef struct {
struct _lv_obj_t * obj;
uint32_t part;
uint32_t id1;
uint32_t id2;
lv_layer_t * layer;
} lv_draw_dsc_base_t;
typedef struct {
lv_draw_unit_t * unit_head;
uint32_t used_memory_for_layers_kb;
#if LV_USE_OS
lv_thread_sync_t sync;
#else
int dispatch_req;
#endif
lv_mutex_t circle_cache_mutex;
bool task_running;
} lv_draw_global_info_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
void lv_draw_init(void);
/**
* Allocate a new draw unit with the given size and appends it to the list of draw units
* @param size the size to allocate. E.g. `sizeof(my_draw_unit_t)`,
* where the first element of `my_draw_unit_t` is `lv_draw_unit_t`.
*/
void * lv_draw_create_unit(size_t size);
lv_draw_task_t * lv_draw_add_task(lv_layer_t * layer, const lv_area_t * coords);
void lv_draw_finalize_task_creation(lv_layer_t * layer, lv_draw_task_t * t);
void lv_draw_dispatch(void);
bool lv_draw_dispatch_layer(struct _lv_display_t * disp, lv_layer_t * layer);
/**
* Wait for a new dispatch request.
* It's blocking if `LV_USE_OS == 0` else it yields
*/
void lv_draw_dispatch_wait_for_request(void);
void lv_draw_dispatch_request(void);
/**
* Find and available draw task
* @param layer the draw ctx to search in
* @param t_prev continue searching from this task
* @param draw_unit_id check the task where `preferred_draw_unit_id` equals this value or `LV_DRAW_UNIT_ID_ANY`
* @return tan available draw task or NULL if there is no any
*/
lv_draw_task_t * lv_draw_get_next_available_task(lv_layer_t * layer, lv_draw_task_t * t_prev, uint8_t draw_unit_id);
/**
* Create a new layer on a parent layer
* @param parent_layer the parent layer to which the layer will be merged when it's rendered
* @param color_format the color format of the layer
* @param area the areas of the layer (absolute coordinates)
* @return the new target_layer or NULL on error
*/
lv_layer_t * lv_draw_layer_create(lv_layer_t * parent_layer, lv_color_format_t color_format, const lv_area_t * area);
/**
* Try to allocate a buffer for the layer.
* @param layer pointer to a layer
* @return pointer to the allocated aligned buffer or NULL on failure
*/
void * lv_draw_layer_alloc_buf(lv_layer_t * layer);
/**
* Got to a pixel at X and Y coordinate on a layer
* @param layer pointer to a layer
* @param x the target X coordinate
* @param y the target X coordinate
* @return `buf` offset to point to the given X and Y coordinate
*/
void * lv_draw_layer_go_to_xy(lv_layer_t * layer, int32_t x, int32_t y);
/**********************
* GLOBAL VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* POST INCLUDES
*********************/
#include "lv_draw_rect.h"
#include "lv_draw_label.h"
#include "lv_draw_image.h"
#include "lv_draw_arc.h"
#include "lv_draw_line.h"
#include "lv_draw_triangle.h"
#include "lv_draw_mask.h"
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_image_buf.h | /**
* @file lv_image_buf.h
*
*/
#ifndef LV_IMAGE_BUF_H
#define LV_IMAGE_BUF_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include <stdbool.h>
#include "../misc/lv_color.h"
#include "../misc/lv_area.h"
/*********************
* DEFINES
*********************/
#define LV_IMAGE_BUF_SIZE_TRUE_COLOR(w, h) ((LV_COLOR_DEPTH / 8) * (w) * (h))
#define LV_IMAGE_BUF_SIZE_TRUE_COLOR_CHROMA_KEYED(w, h) ((LV_COLOR_DEPTH / 8) * (w) * (h))
#define LV_IMAGE_BUF_SIZE_TRUE_COLOR_ALPHA(w, h) (_LV_COLOR_NATIVE_WITH_ALPHA_SIZE * (w) * (h))
/*+ 1: to be sure no fractional row*/
#define LV_IMAGE_BUF_SIZE_ALPHA_1BIT(w, h) (((((w) + 7) / 8) * (h)))
#define LV_IMAGE_BUF_SIZE_ALPHA_2BIT(w, h) (((((w) + 3) / 4) * (h)))
#define LV_IMAGE_BUF_SIZE_ALPHA_4BIT(w, h) (((((w) + 1 ) / 2) * (h)))
#define LV_IMAGE_BUF_SIZE_ALPHA_8BIT(w, h) (((w) * (h)))
/*4 * X: for palette*/
#define LV_IMAGE_BUF_SIZE_INDEXED_1BIT(w, h) (LV_IMAGE_BUF_SIZE_ALPHA_1BIT((w), (h)) + 4 * 2)
#define LV_IMAGE_BUF_SIZE_INDEXED_2BIT(w, h) (LV_IMAGE_BUF_SIZE_ALPHA_2BIT((w), (h)) + 4 * 4)
#define LV_IMAGE_BUF_SIZE_INDEXED_4BIT(w, h) (LV_IMAGE_BUF_SIZE_ALPHA_4BIT((w), (h)) + 4 * 16)
#define LV_IMAGE_BUF_SIZE_INDEXED_8BIT(w, h) (LV_IMAGE_BUF_SIZE_ALPHA_8BIT((w), (h)) + 4 * 256)
#define _LV_ZOOM_INV_UPSCALE 5
/**********************
* TYPEDEFS
**********************/
/**
* The first 8 bit is very important to distinguish the different source types.
* For more info see `lv_image_get_src_type()` in lv_img.c
* On big endian systems the order is reversed so cf and always_zero must be at
* the end of the struct.
*/
#if LV_BIG_ENDIAN_SYSTEM
typedef struct {
uint32_t h : 11; /*Height of the image map*/
uint32_t w : 11; /*Width of the image map*/
uint32_t reserved : 2; /*Reserved to be used later*/
uint32_t always_zero : 3; /*It the upper bits of the first byte. Always zero to look like a
non-printable character*/
uint32_t cf : 5; /*Color format: See `lv_color_format_t`*/
} lv_image_header_t;
#else
typedef struct {
uint32_t cf : 5; /*Color format: See `lv_color_format_t`*/
uint32_t always_zero : 3; /*It the upper bits of the first byte. Always zero to look like a
non-printable character*/
uint32_t format: 8; /*Image format? To be defined by LVGL*/
uint32_t user: 8;
uint32_t reserved: 8; /*Reserved to be used later*/
uint32_t w: 16;
uint32_t h: 16;
uint32_t stride: 16; /*Number of bytes in a row*/
uint32_t reserved_2: 16; /*Reserved to be used later*/
} lv_image_header_t;
#endif
/** Image header it is compatible with
* the result from image converter utility*/
typedef struct {
lv_image_header_t header; /**< A header describing the basics of the image*/
uint32_t data_size; /**< Size of the image in bytes*/
const uint8_t * data; /**< Pointer to the data of the image*/
} lv_image_dsc_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Set the palette color of an indexed image. Valid only for `LV_IMAGE_CF_INDEXED1/2/4/8`
* @param dsc pointer to an image descriptor
* @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 in lv_color32_t format
*/
void lv_image_buf_set_palette(lv_image_dsc_t * dsc, uint8_t id, lv_color32_t c);
/**
* Free an allocated image buffer
* @param dsc image buffer to free
*/
void lv_image_buf_free(lv_image_dsc_t * dsc);
/**
* Get the area of a rectangle if its rotated and scaled
* @param res store the coordinates here
* @param w width of the rectangle to transform
* @param h height of the rectangle to transform
* @param angle angle of rotation
* @param scale_x zoom in x direction, (256 no zoom)
* @param scale_y zoom in y direction, (256 no zoom)
* @param pivot x,y pivot coordinates of rotation
*/
void _lv_image_buf_get_transformed_area(lv_area_t * res, int32_t w, int32_t h, int32_t angle, uint16_t scale_x,
uint16_t scale_y,
const lv_point_t * pivot);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_IMAGE_BUF_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_draw_rect.h | /**
* @file lv_draw_rect.h
*
*/
#ifndef LV_DRAW_RECT_H
#define LV_DRAW_RECT_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "lv_draw.h"
#include "../misc/lv_color.h"
#include "../misc/lv_area.h"
#include "../misc/lv_style.h"
#include "sw/lv_draw_sw_gradient.h"
/*********************
* DEFINES
*********************/
#define LV_RADIUS_CIRCLE 0x7FFF /**< A very big radius to always draw as circle*/
LV_EXPORT_CONST_INT(LV_RADIUS_CIRCLE);
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_draw_dsc_base_t base;
int32_t radius;
/*Background*/
lv_opa_t bg_opa;
lv_color_t bg_color; /**< First element of a gradient is a color, so it maps well here*/
lv_grad_dsc_t bg_grad;
/*Background img*/
const void * bg_image_src;
const void * bg_image_symbol_font;
lv_color_t bg_image_recolor;
lv_opa_t bg_image_opa;
lv_opa_t bg_image_recolor_opa;
uint8_t bg_image_tiled;
/*Border*/
lv_color_t border_color;
int32_t border_width;
lv_opa_t border_opa;
lv_border_side_t border_side : 5;
uint8_t border_post : 1; /*The border will be drawn later*/
/*Outline*/
lv_color_t outline_color;
int32_t outline_width;
int32_t outline_pad;
lv_opa_t outline_opa;
/*Shadow*/
lv_color_t shadow_color;
int32_t shadow_width;
int32_t shadow_offset_x;
int32_t shadow_offset_y;
int32_t shadow_spread;
lv_opa_t shadow_opa;
} lv_draw_rect_dsc_t;
typedef struct {
lv_draw_dsc_base_t base;
int32_t radius;
lv_opa_t opa;
lv_color_t color;
lv_grad_dsc_t grad;
} lv_draw_fill_dsc_t;
typedef struct {
lv_draw_dsc_base_t base;
int32_t radius;
const void * src;
const void * font;
lv_color_t recolor;
lv_opa_t opa;
lv_opa_t recolor_opa;
lv_image_header_t img_header; /*To make it easier for draw_unit to decide if they can draw this image */
uint8_t tiled : 1;
} lv_draw_bg_image_dsc_t;
typedef struct {
lv_draw_dsc_base_t base;
int32_t radius;
lv_color_t color;
int32_t width;
lv_opa_t opa;
lv_border_side_t side : 5;
} lv_draw_border_dsc_t;
typedef struct {
lv_draw_dsc_base_t base;
int32_t radius;
lv_color_t color;
int32_t width;
int32_t spread;
int32_t ofs_x;
int32_t ofs_y;
lv_opa_t opa;
uint8_t bg_cover : 1;
} lv_draw_box_shadow_dsc_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
LV_ATTRIBUTE_FAST_MEM void lv_draw_rect_dsc_init(lv_draw_rect_dsc_t * dsc);
void lv_draw_fill_dsc_init(lv_draw_fill_dsc_t * dsc);
void lv_draw_border_dsc_init(lv_draw_border_dsc_t * dsc);
void lv_draw_box_shadow_dsc_init(lv_draw_box_shadow_dsc_t * dsc);
void lv_draw_bg_image_dsc_init(lv_draw_bg_image_dsc_t * dsc);
/**
* Draw a rectangle
* @param layer pointer to a layer
* @param dsc pointer to an initialized `lv_draw_rect_dsc_t` variable
* @param coords the coordinates of the rectangle
*/
void lv_draw_rect(struct _lv_layer_t * layer, const lv_draw_rect_dsc_t * dsc, const lv_area_t * coords);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_RECT_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_image_decoder.c | /**
* @file lv_image_decoder.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_image_decoder.h"
#include "../misc/lv_assert.h"
#include "../draw/lv_draw_image.h"
#include "../misc/lv_ll.h"
#include "../stdlib/lv_string.h"
#include "../core/lv_global.h"
/*********************
* DEFINES
*********************/
#define img_decoder_ll_p &(LV_GLOBAL_DEFAULT()->img_decoder_ll)
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_fs_file_t f;
lv_color32_t * palette;
uint8_t * img_data;
lv_opa_t * opa;
} lv_image_decoder_built_in_data_t;
/**********************
* STATIC PROTOTYPES
**********************/
static lv_result_t decode_indexed_line(lv_color_format_t color_format, const lv_color32_t * palette, int32_t x,
int32_t y,
int32_t w_px, const uint8_t * in, lv_color32_t * out);
static uint32_t img_width_to_stride(lv_image_header_t * header);
static lv_fs_res_t fs_read_file_at(lv_fs_file_t * f, uint32_t pos, uint8_t * buff, uint32_t btr, uint32_t * br);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Initialize the image decoder module
*/
void _lv_image_decoder_init(void)
{
_lv_ll_init(img_decoder_ll_p, sizeof(lv_image_decoder_t));
lv_image_decoder_t * decoder;
/*Create a decoder for the built in color format*/
decoder = lv_image_decoder_create();
LV_ASSERT_MALLOC(decoder);
if(decoder == NULL) {
LV_LOG_WARN("out of memory");
return;
}
lv_image_decoder_set_info_cb(decoder, lv_image_decoder_built_in_info);
lv_image_decoder_set_open_cb(decoder, lv_image_decoder_built_in_open);
lv_image_decoder_set_get_area_cb(decoder, lv_image_decoder_built_in_get_area);
lv_image_decoder_set_close_cb(decoder, lv_image_decoder_built_in_close);
}
/**
* Get information about an image.
* Try the created image decoder one by one. Once one is able to get info that info will be used.
* @param src the image source. E.g. file name or variable.
* @param header the image info will be stored here
* @return LV_RESULT_OK: success; LV_RESULT_INVALID: wasn't able to get info about the image
*/
lv_result_t lv_image_decoder_get_info(const void * src, lv_image_header_t * header)
{
lv_memzero(header, sizeof(lv_image_header_t));
if(src == NULL) return LV_RESULT_INVALID;
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;
if(img_dsc->data == NULL) return LV_RESULT_INVALID;
}
lv_result_t res = LV_RESULT_INVALID;
lv_image_decoder_t * decoder;
_LV_LL_READ(img_decoder_ll_p, decoder) {
if(decoder->info_cb) {
res = decoder->info_cb(decoder, src, header);
if(res == LV_RESULT_OK) {
if(header->stride == 0) header->stride = img_width_to_stride(header);
break;
}
}
}
return res;
}
lv_result_t lv_image_decoder_open(lv_image_decoder_dsc_t * dsc, const void * src, lv_color_t color, int32_t frame_id)
{
LV_UNUSED(color);
lv_memzero(dsc, sizeof(lv_image_decoder_dsc_t));
if(src == NULL) return LV_RESULT_INVALID;
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;
if(img_dsc->data == NULL) return LV_RESULT_INVALID;
}
dsc->src_type = src_type;
dsc->frame_id = frame_id;
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
size_t fnlen = lv_strlen(src);
dsc->src = lv_malloc(fnlen + 1);
LV_ASSERT_MALLOC(dsc->src);
if(dsc->src == NULL) {
LV_LOG_WARN("out of memory");
return LV_RESULT_INVALID;
}
lv_strcpy((char *)dsc->src, src);
}
else {
dsc->src = src;
}
lv_result_t res = LV_RESULT_INVALID;
lv_image_decoder_t * decoder;
_LV_LL_READ(img_decoder_ll_p, decoder) {
/*Info and Open callbacks are required*/
if(decoder->info_cb == NULL || decoder->open_cb == NULL) continue;
res = decoder->info_cb(decoder, src, &dsc->header);
if(res != LV_RESULT_OK) continue;
if(dsc->header.stride == 0) dsc->header.stride = img_width_to_stride(&dsc->header);
dsc->decoder = decoder;
res = decoder->open_cb(decoder, dsc);
/*Opened successfully. It is a good decoder for this image source*/
if(res == LV_RESULT_OK) return res;
/*Prepare for the next loop*/
lv_memzero(&dsc->header, sizeof(lv_image_header_t));
dsc->error_msg = NULL;
dsc->img_data = NULL;
dsc->cache_entry = NULL;
dsc->user_data = NULL;
dsc->time_to_open = 0;
}
if(dsc->src_type == LV_IMAGE_SRC_FILE)
lv_free((void *)dsc->src);
return res;
}
/**
* Decode an area of image
* @param decoder pointer to the decoder where this function belongs
* @param dsc pointer to `lv_image_decoder_dsc_t` used in `lv_image_decoder_open`
* @param full_area full image area information
* @param decoded_area area information to decode (x1, y1, x2, y2)
* @return LV_RESULT_OK: no error; LV_RESULT_INVALID: can't decode image area
*/
lv_result_t lv_image_decoder_get_area(lv_image_decoder_dsc_t * dsc, const lv_area_t * full_area,
lv_area_t * decoded_area)
{
lv_result_t res = LV_RESULT_INVALID;
if(dsc->decoder->get_area_cb) res = dsc->decoder->get_area_cb(dsc->decoder, dsc, full_area, decoded_area);
return res;
}
/**
* Close a decoding session
* @param dsc pointer to `lv_image_decoder_dsc_t` used in `lv_image_decoder_open`
*/
void lv_image_decoder_close(lv_image_decoder_dsc_t * dsc)
{
if(dsc->decoder) {
if(dsc->decoder->close_cb) dsc->decoder->close_cb(dsc->decoder, dsc);
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
lv_free((void *)dsc->src);
dsc->src = NULL;
}
}
}
/**
* Create a new image decoder
* @return pointer to the new image decoder
*/
lv_image_decoder_t * lv_image_decoder_create(void)
{
lv_image_decoder_t * decoder;
decoder = _lv_ll_ins_head(img_decoder_ll_p);
LV_ASSERT_MALLOC(decoder);
if(decoder == NULL) return NULL;
lv_memzero(decoder, sizeof(lv_image_decoder_t));
return decoder;
}
/**
* Delete an image decoder
* @param decoder pointer to an image decoder
*/
void lv_image_decoder_delete(lv_image_decoder_t * decoder)
{
_lv_ll_remove(img_decoder_ll_p, decoder);
lv_free(decoder);
}
/**
* Get the next image decoder in the linked list of image decoders
* @param decoder pointer to an image decoder
* @return the next image decoder or NULL if no more image decoder exists
*/
lv_image_decoder_t * lv_image_decoder_get_next(lv_image_decoder_t * decoder)
{
if(decoder == NULL)
return _lv_ll_get_head(img_decoder_ll_p);
else
return _lv_ll_get_next(img_decoder_ll_p, decoder);
}
/**
* Set a callback to get information about the image
* @param decoder pointer to an image decoder
* @param info_cb a function to collect info about an image (fill an `lv_image_header_t` struct)
*/
void lv_image_decoder_set_info_cb(lv_image_decoder_t * decoder, lv_image_decoder_info_f_t info_cb)
{
decoder->info_cb = info_cb;
}
/**
* Set a callback to open an image
* @param decoder pointer to an image decoder
* @param open_cb a function to open an image
*/
void lv_image_decoder_set_open_cb(lv_image_decoder_t * decoder, lv_image_decoder_open_f_t open_cb)
{
decoder->open_cb = open_cb;
}
/**
* Set a callback to get decoded area of an image
* @param decoder pointer to an image decoder
* @param get_area_cb a function to get area of an image
*/
void lv_image_decoder_set_get_area_cb(lv_image_decoder_t * decoder, lv_image_decoder_get_area_cb_t get_area_cb)
{
decoder->get_area_cb = get_area_cb;
}
/**
* Set a callback to close a decoding session. E.g. close files and free other resources.
* @param decoder pointer to an image decoder
* @param close_cb a function to close a decoding session
*/
void lv_image_decoder_set_close_cb(lv_image_decoder_t * decoder, lv_image_decoder_close_f_t close_cb)
{
decoder->close_cb = close_cb;
}
/**
* Get info about a built-in image
* @param decoder the decoder where this function belongs
* @param src the image source: pointer to an `lv_image_dsc_t` variable, a file path or a symbol
* @param header store the image data here
* @return LV_RESULT_OK: the info is successfully stored in `header`; LV_RESULT_INVALID: unknown format or other error.
*/
lv_result_t lv_image_decoder_built_in_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);
if(src_type == LV_IMAGE_SRC_VARIABLE) {
header->w = ((lv_image_dsc_t *)src)->header.w;
header->h = ((lv_image_dsc_t *)src)->header.h;
header->cf = ((lv_image_dsc_t *)src)->header.cf;
header->stride = ((lv_image_dsc_t *)src)->header.stride;
}
else if(src_type == LV_IMAGE_SRC_FILE) {
/*Support only "*.bin" files*/
if(strcmp(lv_fs_get_ext(src), "bin")) return LV_RESULT_INVALID;
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) {
uint32_t rn;
res = lv_fs_read(&f, header, sizeof(lv_image_header_t), &rn);
lv_fs_close(&f);
if(res != LV_FS_RES_OK || rn != sizeof(lv_image_header_t)) {
LV_LOG_WARN("Image get info get read file header");
return LV_RESULT_INVALID;
}
}
}
else if(src_type == LV_IMAGE_SRC_SYMBOL) {
/*The size depend on the font but it is unknown here. It should be handled outside of the
*function*/
header->w = 1;
header->h = 1;
/*Symbols always have transparent parts. Important because of cover check in the draw
*function. The actual value doesn't matter because lv_draw_label will draw it*/
header->cf = LV_COLOR_FORMAT_A8;
}
else {
LV_LOG_WARN("Image get info found unknown src type");
return LV_RESULT_INVALID;
}
return LV_RESULT_OK;
}
static lv_image_decoder_built_in_data_t * get_decoder_data(lv_image_decoder_dsc_t * dsc)
{
lv_image_decoder_built_in_data_t * data = dsc->user_data;
if(data == NULL) {
data = lv_malloc(sizeof(lv_image_decoder_built_in_data_t));
LV_ASSERT_MALLOC(data);
if(data == NULL) {
LV_LOG_ERROR("out of memory");
return NULL;
}
lv_memzero(data, sizeof(lv_image_decoder_built_in_data_t));
dsc->user_data = data;
}
return data;
}
static lv_result_t decode_indexed(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder); /*Unused*/
lv_result_t res;
uint32_t rn;
lv_image_decoder_built_in_data_t * decoder_data = dsc->user_data;
lv_fs_file_t * f = &decoder_data->f;
lv_color_format_t cf = dsc->header.cf;
/*read palette for indexed image*/
uint32_t palette_len = sizeof(lv_color32_t) * LV_COLOR_INDEXED_PALETTE_SIZE(cf);
lv_color32_t * palette = lv_malloc(palette_len);
LV_ASSERT_MALLOC(palette);
if(palette == NULL) {
LV_LOG_ERROR("out of memory");
return LV_RESULT_INVALID;
}
res = fs_read_file_at(f, sizeof(lv_image_header_t), (uint8_t *)palette, palette_len, &rn);
if(res != LV_FS_RES_OK || rn != palette_len) {
LV_LOG_WARN("read palette failed");
lv_free(palette);
return LV_RESULT_INVALID;
}
dsc->palette = palette;
dsc->palette_size = LV_COLOR_INDEXED_PALETTE_SIZE(cf);
decoder_data->palette = palette; /*Free decoder data on close*/
#if LV_BIN_DECODER_RAM_LOAD
uint32_t stride = dsc->header.stride;
uint8_t * file_buf = lv_draw_buf_malloc(stride * dsc->header.h, cf);
LV_ASSERT_MALLOC(file_buf);
if(file_buf == NULL) {
LV_LOG_ERROR("draw buffer alloc failed");
return LV_RESULT_INVALID;
}
uint32_t data_len = 0;
if(lv_fs_seek(f, 0, LV_FS_SEEK_END) != LV_FS_RES_OK ||
lv_fs_tell(f, &data_len) != LV_FS_RES_OK) {
LV_LOG_WARN("failed to get file to size");
goto exit_with_buf;
}
uint32_t data_offset = sizeof(lv_image_header_t) + palette_len;
data_len -= data_offset;
res = fs_read_file_at(f, data_offset, (uint8_t *)file_buf, data_len, &rn);
if(res != LV_FS_RES_OK || rn != data_len) {
LV_LOG_WARN("read palette failed");
goto exit_with_buf;
}
/*Convert to ARGB8888, since sw renderer cannot render it directly even it's in RAM*/
stride = lv_draw_buf_width_to_stride(dsc->header.w, LV_COLOR_FORMAT_ARGB8888);
uint8_t * img_data = lv_draw_buf_malloc(stride * dsc->header.h, cf);
if(img_data == NULL) {
LV_LOG_ERROR("no memory for indexed image");
goto exit_with_buf;
}
const uint8_t * in = file_buf;
uint8_t * out = img_data;
for(uint32_t y = 0; y < dsc->header.h; y++) {
decode_indexed_line(cf, dsc->palette, 0, 0, dsc->header.w, in, (lv_color32_t *)out);
in += dsc->header.stride;
out += stride;
}
dsc->header.stride = stride;
dsc->header.cf = LV_COLOR_FORMAT_ARGB8888;
dsc->img_data = img_data;
decoder_data->img_data = img_data; /*Free when decoder closes*/
lv_draw_buf_free(file_buf);
return LV_RESULT_OK;
exit_with_buf:
lv_free(palette);
lv_draw_buf_free(file_buf);
return LV_RESULT_INVALID;
#else
/*It needs to be read by get_area_cb later*/
return LV_RESULT_OK;
#endif
}
#if LV_BIN_DECODER_RAM_LOAD
static lv_result_t decode_rgb(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder);
lv_result_t res;
lv_image_decoder_built_in_data_t * decoder_data = dsc->user_data;
lv_fs_file_t * f = &decoder_data->f;
lv_color_format_t cf = dsc->header.cf;
uint32_t len = dsc->header.stride * dsc->header.h;
if(cf == LV_COLOR_FORMAT_RGB565A8) {
len += dsc->header.w * dsc->header.h * 1;
}
uint8_t * img_data = lv_draw_buf_malloc(len, cf);
LV_ASSERT_MALLOC(img_data);
if(img_data == NULL) {
LV_LOG_ERROR("no memory for rgb file read");
return LV_RESULT_INVALID;
}
uint32_t rn;
res = fs_read_file_at(f, sizeof(lv_image_header_t), img_data, len, &rn);
if(res != LV_FS_RES_OK || rn != len) {
LV_LOG_WARN("read rgb file failed");
lv_draw_buf_free(img_data);
return LV_RESULT_INVALID;
}
dsc->img_data = img_data;
decoder_data->img_data = img_data; /*Free when decoder closes*/
return LV_RESULT_OK;
}
#endif
static lv_result_t decode_alpha_only(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder);
lv_result_t res;
uint32_t rn;
lv_image_decoder_built_in_data_t * decoder_data = dsc->user_data;
uint8_t bpp = lv_color_format_get_bpp(dsc->header.cf);
uint32_t w = (dsc->header.stride * 8) / bpp;
uint32_t buf_stride = (w * 8 + 7) >> 3; /*stride for img_data*/
uint32_t buf_len = w * dsc->header.h; /*always decode to A8 format*/
uint8_t * img_data = lv_draw_buf_malloc(buf_len, dsc->header.cf);
uint32_t file_len = (uint32_t)dsc->header.stride * dsc->header.h;
LV_ASSERT_MALLOC(img_data);
if(img_data == NULL) {
LV_LOG_ERROR("out of memory");
return LV_RESULT_INVALID;
}
res = fs_read_file_at(&decoder_data->f, sizeof(lv_image_header_t), img_data, file_len, &rn);
if(res != LV_FS_RES_OK || rn != file_len) {
LV_LOG_WARN("Built-in image decoder can't read the palette");
lv_draw_buf_free(img_data);
return LV_RESULT_INVALID;
}
if(dsc->header.cf != LV_COLOR_FORMAT_A8) {
/*Convert A1/2/4 to A8 from last pixel to first pixel*/
uint8_t * in = img_data + file_len - 1;
uint8_t * out = img_data + buf_len - 1;
uint8_t mask = (1 << bpp) - 1;
uint8_t shift = 0;
for(uint32_t i = 0; i < buf_len; i++) {
*out = ((*in >> shift) & mask) << (8 - bpp);
shift += bpp;
if(shift >= 8) {
shift = 0;
in--;
}
out--;
}
}
decoder_data->img_data = img_data;
dsc->img_data = img_data;
dsc->header.stride = buf_stride;
dsc->header.cf = LV_COLOR_FORMAT_A8;
return LV_RESULT_OK;
}
/**
* Open a built in image
* @param decoder the decoder where this function belongs
* @param dsc pointer to decoder descriptor. `src`, `color` are already initialized in it.
* @return LV_RESULT_OK: the info is successfully stored in `header`; LV_RESULT_INVALID: unknown format or other error.
*/
lv_result_t lv_image_decoder_built_in_open(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder);
/*Open the file if it's a file*/
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
/*Support only "*.bin" files*/
if(strcmp(lv_fs_get_ext(dsc->src), "bin")) return LV_RESULT_INVALID;
lv_fs_file_t f;
lv_fs_res_t res = lv_fs_open(&f, dsc->src, LV_FS_MODE_RD);
if(res != LV_FS_RES_OK) {
LV_LOG_WARN("open file failed");
return LV_RESULT_INVALID;
}
/*If the file was open successfully save the file descriptor*/
lv_image_decoder_built_in_data_t * decoder_data = get_decoder_data(dsc);
if(decoder_data == NULL) {
return LV_RESULT_INVALID;
}
lv_memcpy(&decoder_data->f, &f, sizeof(f));
dsc->user_data = decoder_data;
lv_color_format_t cf = dsc->header.cf;
/*Palette for indexed image and whole image of A8 image are always loaded to RAM for simplicity*/
if(LV_COLOR_FORMAT_IS_INDEXED(cf)) {
res = decode_indexed(decoder, dsc);
}
else if(LV_COLOR_FORMAT_IS_ALPHA_ONLY(cf)) {
res = decode_alpha_only(decoder, dsc);
}
#if LV_BIN_DECODER_RAM_LOAD
else if(cf == LV_COLOR_FORMAT_ARGB8888 || cf == LV_COLOR_FORMAT_XRGB8888
|| cf == LV_COLOR_FORMAT_RGB888 || cf == LV_COLOR_FORMAT_RGB565) {
res = decode_rgb(decoder, dsc);
}
else if(cf == LV_COLOR_FORMAT_RGB565A8) {
res = decode_rgb(decoder, dsc);
}
#else
else {
/* decode them in get_area_cb */
res = LV_RESULT_OK;
}
#endif
if(res != LV_RESULT_OK) {
lv_fs_close(&f);
lv_memset(&decoder_data->f, 0, sizeof(decoder_data->f));
}
return res;
}
if(dsc->src_type == LV_IMAGE_SRC_VARIABLE) {
/*The variables should have valid data*/
lv_image_dsc_t * img_dsc = (lv_image_dsc_t *)dsc->src;
if(img_dsc->data == NULL) {
return LV_RESULT_INVALID;
}
lv_color_format_t cf = img_dsc->header.cf;
if(LV_COLOR_FORMAT_IS_INDEXED(cf)) {
/*Need decoder data to store converted image*/
lv_image_decoder_built_in_data_t * decoder_data = get_decoder_data(dsc);
if(decoder_data == NULL) {
return LV_RESULT_INVALID;
}
uint8_t * img_data = lv_draw_buf_malloc(sizeof(lv_color32_t) * img_dsc->header.w * img_dsc->header.h,
img_dsc->header.cf);
LV_ASSERT_NULL(img_data);
if(img_data == NULL) {
return LV_RESULT_INVALID;
}
decoder_data->img_data = img_data; /*Put to decoder data for later free*/
/*Assemble the decoded image dsc*/
uint32_t palette_size = LV_COLOR_INDEXED_PALETTE_SIZE(cf);
dsc->palette_size = palette_size;
dsc->palette = (const lv_color32_t *)img_dsc->data;
dsc->img_data = img_data; /*Return decoded image data.*/
dsc->header.cf = LV_COLOR_FORMAT_ARGB8888;
dsc->header.stride = dsc->header.w * 4;
uint32_t y;
lv_color32_t * out = (lv_color32_t *) dsc->img_data;
const uint8_t * in = img_dsc->data;
in += palette_size * 4;
for(y = 0; y < img_dsc->header.h; y++) {
decode_indexed_line(cf, dsc->palette, 0, y, img_dsc->header.w, in, out);
}
}
else {
/*In case of uncompressed formats the image stored in the ROM/RAM.
*So simply give its pointer*/
dsc->img_data = ((lv_image_dsc_t *)dsc->src)->data;
}
return LV_RESULT_OK;
}
return LV_RESULT_INVALID;
}
/**
* Close the pending decoding. Free resources etc.
* @param decoder pointer to the decoder the function associated with
* @param dsc pointer to decoder descriptor
*/
void lv_image_decoder_built_in_close(lv_image_decoder_t * decoder, lv_image_decoder_dsc_t * dsc)
{
LV_UNUSED(decoder); /*Unused*/
lv_image_decoder_built_in_data_t * decoder_data = dsc->user_data;
if(decoder_data) {
if(dsc->src_type == LV_IMAGE_SRC_FILE) {
lv_fs_close(&decoder_data->f);
}
lv_draw_buf_free(decoder_data->img_data);
lv_free(decoder_data->palette);
lv_free(decoder_data);
}
}
lv_result_t lv_image_decoder_built_in_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); /*Unused*/
lv_color_format_t cf = dsc->header.cf;
/*Check if cf is supported*/
bool supported = LV_COLOR_FORMAT_IS_INDEXED(cf)
|| cf == LV_COLOR_FORMAT_ARGB8888 || cf == LV_COLOR_FORMAT_XRGB8888 || cf == LV_COLOR_FORMAT_RGB888
|| cf == LV_COLOR_FORMAT_RGB565 || cf == LV_COLOR_FORMAT_RGB565A8;
if(!supported) {
LV_LOG_WARN("CF: %d is not supported", cf);
return LV_RESULT_INVALID;
}
lv_result_t res = LV_RESULT_INVALID;
lv_image_decoder_built_in_data_t * decoder_data = dsc->user_data;
lv_fs_file_t * f = &decoder_data->f;
uint32_t bpp = lv_color_format_get_bpp(cf);
int32_t w_px = lv_area_get_width(full_area);
uint8_t * img_data = NULL;
uint32_t offset = sizeof(lv_image_header_t); /*All image starts with image header*/
/*We only support read line by line for now*/
if(decoded_area->y1 == LV_COORD_MIN) {
/*Indexed image is converted to ARGB888*/
uint32_t len = LV_COLOR_FORMAT_IS_INDEXED(cf) ? sizeof(lv_color32_t) * 8 : bpp;
len = (len * w_px) / 8;
img_data = lv_draw_buf_malloc(len, cf);
LV_ASSERT_NULL(img_data);
if(img_data == NULL)
return LV_RESULT_INVALID;
*decoded_area = *full_area;
decoded_area->y2 = decoded_area->y1;
decoder_data->img_data = img_data; /*Free on decoder close*/
}
else {
decoded_area->y1++;
decoded_area->y2++;
img_data = decoder_data->img_data;
}
if(decoded_area->y1 > full_area->y2) {
return LV_RESULT_INVALID;
}
if(LV_COLOR_FORMAT_IS_INDEXED(cf)) {
int32_t x_fraction = decoded_area->x1 % (8 / bpp);
uint32_t len = (w_px * bpp + 7) / 8 + 1; /*10px for 1bpp may across 3bytes*/
uint8_t * buf = lv_malloc(len);
LV_ASSERT_NULL(buf);
if(buf == NULL)
return LV_RESULT_INVALID;
offset += dsc->palette_size * 4; /*Skip palette*/
offset += decoded_area->y1 * ((dsc->header.w * bpp + 7) / 8); /*Move to y1*/
offset += decoded_area->x1 * bpp / 8; /*Move to x1*/
res = fs_read_file_at(f, offset, buf, len, NULL);
if(res != LV_FS_RES_OK) {
lv_free(buf);
return LV_RESULT_INVALID;
}
decode_indexed_line(cf, dsc->palette, x_fraction, 0, w_px, buf, (lv_color32_t *)img_data);
lv_free(buf);
dsc->img_data = img_data; /*Return decoded image*/
return LV_RESULT_OK;
}
if(cf == LV_COLOR_FORMAT_ARGB8888 || cf == LV_COLOR_FORMAT_XRGB8888 || cf == LV_COLOR_FORMAT_RGB888
|| cf == LV_COLOR_FORMAT_RGB565) {
uint32_t len = (w_px * bpp) / 8;
offset += decoded_area->y1 * dsc->header.w * bpp / 8; /*Move to y1*/
offset += decoded_area->x1 * bpp / 8; /*Move to x1*/
res = fs_read_file_at(f, offset, img_data, len, NULL);
if(res != LV_FS_RES_OK) {
return LV_RESULT_INVALID;
}
dsc->img_data = img_data; /*Return decoded image*/
return LV_RESULT_OK;
}
if(cf == LV_COLOR_FORMAT_RGB565A8) {
bpp = 16; /* RGB565 + A8 mask*/
uint32_t len = (w_px * bpp) / 8; /*map comes firstly*/
offset += decoded_area->y1 * dsc->header.w * bpp / 8; /*Move to y1*/
offset += decoded_area->x1 * bpp / 8; /*Move to x1*/
res = fs_read_file_at(f, offset, img_data, len, NULL);
if(res != LV_FS_RES_OK) {
return LV_RESULT_INVALID;
}
/*Now the A8 mask*/
offset = sizeof(lv_image_header_t);
offset += dsc->header.h * dsc->header.w * bpp / 8; /*Move to A8 map*/
offset += decoded_area->y1 * dsc->header.w * 1; /*Move to y1*/
offset += decoded_area->x1 * 1; /*Move to x1*/
res = fs_read_file_at(f, offset, img_data + len, w_px * 1, NULL);
if(res != LV_FS_RES_OK) {
return LV_RESULT_INVALID;
}
dsc->img_data = img_data; /*Return decoded image*/
return LV_RESULT_OK;
}
return LV_RESULT_INVALID;
}
/**********************
* STATIC FUNCTIONS
**********************/
static lv_result_t decode_indexed_line(lv_color_format_t color_format, const lv_color32_t * palette, int32_t x,
int32_t y,
int32_t w_px, const uint8_t * in, lv_color32_t * out)
{
uint8_t px_size;
uint16_t mask;
out += w_px * y;
int32_t w_byte = 0;
int8_t shift = 0;
switch(color_format) {
case LV_COLOR_FORMAT_I1:
px_size = 1;
w_byte = (w_px + 7) >> 3; /*E.g. w = 20 -> w = 2 + 1*/
in += w_byte * y; /*First pixel*/
in += x / 8; /*8pixel per byte*/
shift = 7 - (x & 0x7);
break;
case LV_COLOR_FORMAT_I2:
px_size = 2;
w_byte = (w_px + 3) >> 2; /*E.g. w = 13 -> w = 3 + 1 (bytes)*/
in += w_byte * y; /*First pixel*/
in += x / 4; /*4pixel per byte*/
shift = 6 - 2 * (x & 0x3);
break;
case LV_COLOR_FORMAT_I4:
px_size = 4;
w_byte = (w_px + 1) >> 1; /*E.g. w = 13 -> w = 6 + 1 (bytes)*/
in += w_byte * y; /*First pixel*/
in += x / 2; /*2pixel per byte*/
shift = 4 - 4 * (x & 0x1);
break;
case LV_COLOR_FORMAT_I8:
px_size = 8;
w_byte = w_px;
in += w_byte * y; /*First pixel*/
in += x;
shift = 0;
break;
default:
return LV_RESULT_INVALID;
}
mask = (1 << px_size) - 1; /*E.g. px_size = 2; mask = 0x03*/
int32_t i;
for(i = 0; i < w_px; i++) {
uint8_t val_act = (*in >> shift) & mask;
out[i] = palette[val_act];
shift -= px_size;
if(shift < 0) {
shift = 8 - px_size;
in++;
}
}
return LV_RESULT_OK;
}
static uint32_t img_width_to_stride(lv_image_header_t * header)
{
if(header->cf == LV_COLOR_FORMAT_RGB565A8) {
return header->w * 2;
}
else {
return ((uint32_t)header->w * lv_color_format_get_bpp(header->cf) + 7) >> 3;
}
}
static lv_fs_res_t fs_read_file_at(lv_fs_file_t * f, uint32_t pos, uint8_t * buff, uint32_t btr, uint32_t * br)
{
lv_fs_res_t res;
if(br) *br = 0;
res = lv_fs_seek(f, pos, LV_FS_SEEK_SET);
if(res != LV_FS_RES_OK) {
return res;
}
res |= lv_fs_read(f, buff, btr, br);
if(res != LV_FS_RES_OK) {
return res;
}
return LV_FS_RES_OK;
}
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/lv_image_buf.c | /**
* @file lv_image_buf.c
*
*/
/*********************
* INCLUDES
*********************/
#include <stddef.h>
#include <string.h>
#include "lv_image_buf.h"
#include "lv_draw_image.h"
#include "../misc/lv_math.h"
#include "../misc/lv_log.h"
#include "../stdlib/lv_mem.h"
#include "../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_image_buf_set_palette(lv_image_dsc_t * dsc, uint8_t id, lv_color32_t c)
{
if(dsc->header.cf < LV_COLOR_FORMAT_I1 || dsc->header.cf > LV_COLOR_FORMAT_I8) {
LV_LOG_WARN("Not indexed color format");
return;
}
uint8_t * buf = (uint8_t *)dsc->data;
lv_memcpy(&buf[id * sizeof(c)], &c, sizeof(c));
}
void lv_image_buf_free(lv_image_dsc_t * dsc)
{
if(dsc != NULL) {
if(dsc->data != NULL)
lv_free((void *)dsc->data);
lv_free(dsc);
}
}
void _lv_image_buf_get_transformed_area(lv_area_t * res, int32_t w, int32_t h, int32_t angle, uint16_t scale_x,
uint16_t scale_y,
const lv_point_t * pivot)
{
if(angle == 0 && scale_x == LV_SCALE_NONE && scale_y == LV_SCALE_NONE) {
res->x1 = 0;
res->y1 = 0;
res->x2 = w - 1;
res->y2 = h - 1;
return;
}
lv_point_t p[4] = {
{0, 0},
{w - 1, 0},
{0, h - 1},
{w - 1, h - 1},
};
lv_point_transform(&p[0], angle, scale_x, scale_y, pivot, true);
lv_point_transform(&p[1], angle, scale_x, scale_y, pivot, true);
lv_point_transform(&p[2], angle, scale_x, scale_y, pivot, true);
lv_point_transform(&p[3], angle, scale_x, scale_y, pivot, true);
res->x1 = LV_MIN4(p[0].x, p[1].x, p[2].x, p[3].x);
res->x2 = LV_MAX4(p[0].x, p[1].x, p[2].x, p[3].x);
res->y1 = LV_MIN4(p[0].y, p[1].y, p[2].y, p[3].y);
res->y2 = LV_MAX4(p[0].y, p[1].y, p[2].y, p[3].y);
}
/**********************
* STATIC FUNCTIONS
**********************/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_img.c | /**
* @file lv_draw_sw_img.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_draw_sw.h"
#if LV_USE_DRAW_SW
#include "../../display/lv_display.h"
#include "../../display/lv_display_private.h"
#include "../../misc/lv_log.h"
#include "../../core/lv_refr.h"
#include "../../stdlib/lv_mem.h"
#include "../../misc/lv_cache.h"
#include "../../misc/lv_math.h"
#include "../../misc/lv_color.h"
#include "../../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
#define MAX_BUF_SIZE (uint32_t) 4 * lv_draw_buf_width_to_stride(lv_display_get_horizontal_resolution(_lv_refr_get_disp_refreshing()), lv_display_get_color_format(_lv_refr_get_disp_refreshing()))
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void img_draw_core(lv_draw_unit_t * draw_unit, const lv_draw_image_dsc_t * draw_dsc, const lv_area_t * draw_area,
const lv_image_decoder_dsc_t * src, lv_draw_image_sup_t * sup, const lv_area_t * img_coords);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_sw_layer(lv_draw_unit_t * draw_unit, const lv_draw_image_dsc_t * draw_dsc, const lv_area_t * coords)
{
lv_layer_t * layer_to_draw = (lv_layer_t *)draw_dsc->src;
/*It can happen that nothing was draw on a layer and therefore its buffer is not allocated.
*In this case just return. */
if(layer_to_draw->buf == NULL) return;
lv_image_dsc_t img_dsc;
img_dsc.header.w = lv_area_get_width(&layer_to_draw->buf_area);
img_dsc.header.h = lv_area_get_height(&layer_to_draw->buf_area);
img_dsc.header.cf = layer_to_draw->color_format;
img_dsc.header.stride = lv_draw_buf_width_to_stride(lv_area_get_width(&layer_to_draw->buf_area),
layer_to_draw->color_format);
img_dsc.header.always_zero = 0;
img_dsc.data = lv_draw_buf_align(layer_to_draw->buf, layer_to_draw->color_format);
lv_draw_image_dsc_t new_draw_dsc;
lv_memcpy(&new_draw_dsc, draw_dsc, sizeof(lv_draw_image_dsc_t));
new_draw_dsc.src = &img_dsc;
lv_draw_sw_image(draw_unit, &new_draw_dsc, coords);
#if LV_USE_LAYER_DEBUG || LV_USE_PARALLEL_DRAW_DEBUG
lv_area_t area_rot;
lv_area_copy(&area_rot, coords);
if(draw_dsc->rotation || draw_dsc->scale_x != LV_SCALE_NONE || draw_dsc->scale_y != LV_SCALE_NONE) {
int32_t w = lv_area_get_width(coords);
int32_t h = lv_area_get_height(coords);
_lv_image_buf_get_transformed_area(&area_rot, w, h, draw_dsc->rotation, draw_dsc->scale_x, draw_dsc->scale_y,
&draw_dsc->pivot);
area_rot.x1 += coords->x1;
area_rot.y1 += coords->y1;
area_rot.x2 += coords->x1;
area_rot.y2 += coords->y1;
}
lv_area_t draw_area;
if(!_lv_area_intersect(&draw_area, &area_rot, draw_unit->clip_area)) return;
#endif
#if LV_USE_LAYER_DEBUG
lv_draw_fill_dsc_t fill_dsc;
lv_draw_fill_dsc_init(&fill_dsc);
fill_dsc.color = lv_color_hex(layer_to_draw->color_format == LV_COLOR_FORMAT_ARGB8888 ? 0xff0000 : 0x00ff00);
fill_dsc.opa = LV_OPA_20;
lv_draw_sw_fill(draw_unit, &fill_dsc, &area_rot);
lv_draw_border_dsc_t border_dsc;
lv_draw_border_dsc_init(&border_dsc);
border_dsc.color = fill_dsc.color;
border_dsc.opa = LV_OPA_60;
border_dsc.width = 2;
lv_draw_sw_border(draw_unit, &border_dsc, &area_rot);
#endif
#if LV_USE_PARALLEL_DRAW_DEBUG
uint32_t idx = 0;
lv_display_t * disp = _lv_refr_get_disp_refreshing();
lv_draw_unit_t * draw_unit_tmp = disp->draw_unit_head;
while(draw_unit_tmp != draw_unit) {
draw_unit_tmp = draw_unit_tmp->next;
idx++;
}
lv_draw_rect_dsc_t rect_dsc;
lv_draw_rect_dsc_init(&rect_dsc);
rect_dsc.bg_color = lv_palette_main(idx % _LV_PALETTE_LAST);
rect_dsc.border_color = rect_dsc.bg_color;
rect_dsc.bg_opa = LV_OPA_10;
rect_dsc.border_opa = LV_OPA_100;
rect_dsc.border_width = 2;
lv_draw_sw_rect(draw_unit, &rect_dsc, &area_rot);
lv_point_t txt_size;
lv_text_get_size(&txt_size, "W", LV_FONT_DEFAULT, 0, 0, 100, LV_TEXT_FLAG_NONE);
lv_area_t txt_area;
txt_area.x1 = draw_area.x1;
txt_area.x2 = draw_area.x1 + txt_size.x - 1;
txt_area.y2 = draw_area.y2;
txt_area.y1 = draw_area.y2 - txt_size.y + 1;
lv_draw_rect_dsc_init(&rect_dsc);
rect_dsc.bg_color = lv_color_black();
lv_draw_sw_rect(draw_unit, &rect_dsc, &txt_area);
char buf[8];
lv_snprintf(buf, sizeof(buf), "%d", idx);
lv_draw_label_dsc_t label_dsc;
lv_draw_label_dsc_init(&label_dsc);
label_dsc.color = lv_color_white();
label_dsc.text = buf;
lv_draw_sw_label(draw_unit, &label_dsc, &txt_area);
#endif
}
LV_ATTRIBUTE_FAST_MEM void lv_draw_sw_image(lv_draw_unit_t * draw_unit, const lv_draw_image_dsc_t * draw_dsc,
const lv_area_t * coords)
{
lv_area_t transformed_area;
lv_area_copy(&transformed_area, coords);
if(draw_dsc->rotation || draw_dsc->scale_x != LV_SCALE_NONE || draw_dsc->scale_y != LV_SCALE_NONE) {
int32_t w = lv_area_get_width(coords);
int32_t h = lv_area_get_height(coords);
_lv_image_buf_get_transformed_area(&transformed_area, w, h, draw_dsc->rotation, draw_dsc->scale_x, draw_dsc->scale_y,
&draw_dsc->pivot);
transformed_area.x1 += coords->x1;
transformed_area.y1 += coords->y1;
transformed_area.x2 += coords->x1;
transformed_area.y2 += coords->y1;
}
lv_area_t draw_area; /*Common area of cilp_area and coords. The image is visible only here*/
/*Out of mask. There is nothing to draw so the image is drawn successfully.*/
if(!_lv_area_intersect(&draw_area, draw_unit->clip_area, &transformed_area)) {
return;
}
lv_image_decoder_dsc_t decoder_dsc;
lv_result_t res = lv_image_decoder_open(&decoder_dsc, draw_dsc->src, draw_dsc->recolor, -1);
if(res != LV_RESULT_OK) {
LV_LOG_ERROR("Failed to open image");
return;
}
lv_draw_image_sup_t sup;
sup.alpha_color = draw_dsc->recolor;
sup.palette = decoder_dsc.palette;
sup.palette_size = decoder_dsc.palette_size;
/*The whole image is available, just draw it*/
if(decoder_dsc.img_data) {
img_draw_core(draw_unit, draw_dsc, &draw_area, &decoder_dsc,
&sup, coords);
}
/*Draw line by line*/
else {
lv_area_t relative_full_area_to_decode = draw_area;
lv_area_move(&relative_full_area_to_decode, -coords->x1, -coords->y1);
lv_area_t relative_decoded_area;
relative_decoded_area.x1 = LV_COORD_MIN;
relative_decoded_area.y1 = LV_COORD_MIN;
relative_decoded_area.x2 = LV_COORD_MIN;
relative_decoded_area.y2 = LV_COORD_MIN;
res = LV_RESULT_OK;
while(res == LV_RESULT_OK) {
res = lv_image_decoder_get_area(&decoder_dsc, &relative_full_area_to_decode, &relative_decoded_area);
lv_area_t absolute_decoded_area = relative_decoded_area;
lv_area_move(&absolute_decoded_area, coords->x1, coords->y1);
if(res == LV_RESULT_OK) {
/*Limit draw area to the current decoded area and draw the image*/
lv_area_t draw_area_sub;
if(_lv_area_intersect(&draw_area_sub, &draw_area, &absolute_decoded_area)) {
img_draw_core(draw_unit, draw_dsc, &draw_area_sub, &decoder_dsc,
&sup, &absolute_decoded_area);
}
}
}
}
lv_image_decoder_close(&decoder_dsc);
}
static void img_draw_core(lv_draw_unit_t * draw_unit, const lv_draw_image_dsc_t * draw_dsc, const lv_area_t * draw_area,
const lv_image_decoder_dsc_t * src, lv_draw_image_sup_t * sup, const lv_area_t * img_coords)
{
bool transformed = draw_dsc->rotation != 0 || draw_dsc->scale_x != LV_SCALE_NONE ||
draw_dsc->scale_y != LV_SCALE_NONE ? true : false;
lv_draw_sw_blend_dsc_t blend_dsc;
const uint8_t * src_buf = src->img_data;
const lv_image_header_t * header = &src->header;
uint32_t img_stride = header->stride;
lv_color_format_t cf = header->cf;
cf = LV_COLOR_FORMAT_IS_INDEXED(cf) ? LV_COLOR_FORMAT_ARGB8888 : cf,
lv_memzero(&blend_dsc, sizeof(lv_draw_sw_blend_dsc_t));
blend_dsc.opa = draw_dsc->opa;
blend_dsc.blend_mode = draw_dsc->blend_mode;
blend_dsc.src_stride = img_stride;
if(!transformed && cf == LV_COLOR_FORMAT_A8) {
lv_area_t clipped_coords;
if(!_lv_area_intersect(&clipped_coords, img_coords, draw_unit->clip_area)) return;
blend_dsc.mask_buf = (lv_opa_t *)src_buf;
blend_dsc.mask_area = img_coords;
blend_dsc.mask_stride = img_stride;
blend_dsc.src_buf = NULL;
blend_dsc.color = draw_dsc->recolor;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
blend_dsc.blend_area = img_coords;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
else if(!transformed && cf == LV_COLOR_FORMAT_RGB565A8 && draw_dsc->recolor_opa == LV_OPA_TRANSP) {
int32_t src_h = lv_area_get_height(img_coords);
int32_t src_w = lv_area_get_width(img_coords);
blend_dsc.src_area = img_coords;
blend_dsc.src_buf = src_buf;
blend_dsc.mask_buf = (lv_opa_t *)src_buf;
blend_dsc.mask_buf += img_stride * src_w / header->w * src_h;
blend_dsc.mask_stride = src_w;
blend_dsc.blend_area = img_coords;
blend_dsc.mask_area = img_coords;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
blend_dsc.src_color_format = LV_COLOR_FORMAT_RGB565;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
/*The simplest case just copy the pixels into the draw_buf. Blending will convert the colors if needed*/
else if(!transformed && draw_dsc->recolor_opa == LV_OPA_TRANSP) {
blend_dsc.src_area = img_coords;
blend_dsc.src_buf = src_buf;
blend_dsc.blend_area = img_coords;
blend_dsc.src_color_format = cf;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
/*In the other cases every pixel need to be checked one-by-one*/
else {
lv_area_t blend_area = *draw_area;
blend_dsc.blend_area = &blend_area;
int32_t src_w = lv_area_get_width(img_coords);
int32_t src_h = lv_area_get_height(img_coords);
int32_t blend_w = lv_area_get_width(&blend_area);
int32_t blend_h = lv_area_get_height(&blend_area);
lv_color_format_t cf_final = cf;
if(transformed) {
if(cf == LV_COLOR_FORMAT_RGB888 || cf == LV_COLOR_FORMAT_XRGB8888) cf_final = LV_COLOR_FORMAT_ARGB8888;
if(cf == LV_COLOR_FORMAT_RGB565) cf_final = LV_COLOR_FORMAT_RGB565A8;
}
uint8_t * tmp_buf;
uint32_t px_size = lv_color_format_get_size(cf_final);
int32_t buf_h;
if(cf_final == LV_COLOR_FORMAT_RGB565A8) {
uint32_t buf_stride = lv_draw_buf_width_to_stride(blend_w, LV_COLOR_FORMAT_RGB565);
buf_stride += blend_w; /*For the A8 part which is not stride aligned*/
buf_h = MAX_BUF_SIZE / buf_stride;
if(buf_h > blend_h) buf_h = blend_h;
tmp_buf = lv_draw_buf_malloc(buf_stride * buf_h, LV_COLOR_FORMAT_RGB565A8);
}
else {
uint32_t buf_stride = lv_draw_buf_width_to_stride(blend_w, cf_final);
buf_h = MAX_BUF_SIZE / buf_stride;
if(buf_h > blend_h) buf_h = blend_h;
tmp_buf = lv_draw_buf_malloc(buf_stride * buf_h, cf_final);
}
uint8_t * tmp_buf_aligned = lv_draw_buf_align(tmp_buf, cf_final);
blend_dsc.src_buf = tmp_buf_aligned;
blend_dsc.src_color_format = cf_final;
int32_t y_last = blend_area.y2;
blend_area.y2 = blend_area.y1 + buf_h - 1;
blend_dsc.src_area = &blend_area;
if(cf_final == LV_COLOR_FORMAT_RGB565A8) {
/*RGB565A8 images will blended as RGB565 + mask
*Therefore the stride can be different. */
blend_dsc.src_stride = lv_draw_buf_width_to_stride(blend_w, LV_COLOR_FORMAT_RGB565);
blend_dsc.mask_buf = tmp_buf_aligned + lv_draw_buf_width_to_stride(blend_w, LV_COLOR_FORMAT_RGB565) * buf_h;
blend_dsc.mask_stride = blend_w;
blend_dsc.mask_area = &blend_area;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
blend_dsc.src_color_format = LV_COLOR_FORMAT_RGB565;
}
else if(cf_final == LV_COLOR_FORMAT_A8) {
blend_dsc.mask_buf = blend_dsc.src_buf;
blend_dsc.mask_stride = blend_w;
blend_dsc.mask_area = &blend_area;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
blend_dsc.color = draw_dsc->recolor;
blend_dsc.src_buf = NULL;
}
else {
blend_dsc.src_stride = lv_draw_buf_width_to_stride(blend_w, cf_final);
}
while(blend_area.y1 <= y_last) {
/*Apply transformations if any or separate the channels*/
lv_area_t relative_area;
lv_area_copy(&relative_area, &blend_area);
lv_area_move(&relative_area, -img_coords->x1, -img_coords->y1);
if(transformed) {
lv_draw_sw_transform(draw_unit, &relative_area, src_buf, src_w, src_h, img_stride,
draw_dsc, sup, cf, tmp_buf_aligned);
}
else if(draw_dsc->recolor_opa >= LV_OPA_MIN) {
int32_t h = lv_area_get_height(&relative_area);
if(cf_final == LV_COLOR_FORMAT_RGB565A8) {
uint32_t stride_px = img_stride / 2;
const uint8_t * rgb_src_buf = src_buf + stride_px * 2 * relative_area.y1 + relative_area.x1 * 2;
const uint8_t * a_src_buf = src_buf + stride_px * 2 * src_h + stride_px * relative_area.y1 +
relative_area.x1;
uint8_t * rgb_dest_buf = tmp_buf_aligned;
uint8_t * a_dest_buf = (uint8_t *)blend_dsc.mask_buf;
int32_t i;
for(i = 0; i < h; i++) {
lv_memcpy(rgb_dest_buf, rgb_src_buf, blend_w * 2);
lv_memcpy(a_dest_buf, a_src_buf, blend_w);
rgb_src_buf += stride_px * 2;
a_src_buf += stride_px;
rgb_dest_buf += blend_w * 2;
a_dest_buf += blend_w;
}
}
else if(cf_final != LV_COLOR_FORMAT_A8) {
const uint8_t * src_buf_tmp = src_buf + img_stride * relative_area.y1 + relative_area.x1 * px_size;
uint8_t * dest_buf_tmp = tmp_buf_aligned;
int32_t i;
for(i = 0; i < h; i++) {
lv_memcpy(dest_buf_tmp, src_buf_tmp, blend_w * px_size);
dest_buf_tmp += blend_w * px_size;
src_buf_tmp += img_stride;
}
}
}
/*Apply recolor*/
if(draw_dsc->recolor_opa > LV_OPA_MIN) {
lv_color_t color = draw_dsc->recolor;
lv_opa_t mix = draw_dsc->recolor_opa;
lv_opa_t mix_inv = 255 - mix;
if(cf_final == LV_COLOR_FORMAT_RGB565A8 || cf_final == LV_COLOR_FORMAT_RGB565) {
uint16_t c_mult[3];
c_mult[0] = (color.blue >> 3) * mix;
c_mult[1] = (color.green >> 2) * mix;
c_mult[2] = (color.red >> 3) * mix;
uint16_t * buf16 = (uint16_t *)tmp_buf_aligned;
int32_t i;
int32_t size = lv_draw_buf_width_to_stride(blend_w, LV_COLOR_FORMAT_RGB565) / 2 * lv_area_get_height(&blend_area);
for(i = 0; i < size; i++) {
buf16[i] = (((c_mult[2] + ((buf16[i] >> 11) & 0x1F) * mix_inv) << 3) & 0xF800) +
(((c_mult[1] + ((buf16[i] >> 5) & 0x3F) * mix_inv) >> 3) & 0x07E0) +
((c_mult[0] + (buf16[i] & 0x1F) * mix_inv) >> 8);
}
}
else if(cf_final != LV_COLOR_FORMAT_A8) {
uint32_t size = lv_area_get_size(&blend_area);
uint32_t i;
uint16_t c_mult[3];
c_mult[0] = color.blue * mix;
c_mult[1] = color.green * mix;
c_mult[2] = color.red * mix;
uint8_t * tmp_buf_2 = tmp_buf_aligned;
for(i = 0; i < size * px_size; i += px_size) {
tmp_buf_2[i + 0] = (c_mult[0] + (tmp_buf_2[i + 0] * mix_inv)) >> 8;
tmp_buf_2[i + 1] = (c_mult[1] + (tmp_buf_2[i + 1] * mix_inv)) >> 8;
tmp_buf_2[i + 2] = (c_mult[2] + (tmp_buf_2[i + 2] * mix_inv)) >> 8;
}
}
}
/*Blend*/
lv_draw_sw_blend(draw_unit, &blend_dsc);
/*Go to the next lines*/
blend_area.y1 = blend_area.y2 + 1;
blend_area.y2 = blend_area.y1 + buf_h - 1;
if(blend_area.y2 > y_last) {
blend_area.y2 = y_last;
if(cf_final == LV_COLOR_FORMAT_RGB565A8) {
blend_dsc.mask_buf = tmp_buf_aligned + lv_draw_buf_width_to_stride(blend_w,
LV_COLOR_FORMAT_RGB565) * lv_area_get_height(&blend_area);
}
}
}
lv_draw_buf_free(tmp_buf);
}
}
/**********************
* STATIC FUNCTIONS
**********************/
#endif /*LV_USE_DRAW_SW*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_bg_img.c | /**
* @file lv_draw_sw_bg_img.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_draw_sw.h"
#if LV_USE_DRAW_SW
#include "blend/lv_draw_sw_blend.h"
#include "../../misc/lv_math.h"
#include "../../misc/lv_text_ap.h"
#include "../../core/lv_refr.h"
#include "../../misc/lv_assert.h"
#include "../lv_draw_mask.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_sw_bg_image(lv_draw_unit_t * draw_unit, const lv_draw_bg_image_dsc_t * dsc, const lv_area_t * coords)
{
if(dsc->src == NULL) return;
if(dsc->opa <= LV_OPA_MIN) return;
lv_area_t clip_area;
if(!_lv_area_intersect(&clip_area, coords, draw_unit->clip_area)) {
return;
}
const lv_area_t * clip_area_ori = draw_unit->clip_area;
draw_unit->clip_area = &clip_area;
lv_image_src_t src_type = lv_image_src_get_type(dsc->src);
if(src_type == LV_IMAGE_SRC_SYMBOL) {
lv_point_t size;
lv_text_get_size(&size, dsc->src, dsc->font, 0, 0, LV_COORD_MAX, LV_TEXT_FLAG_NONE);
lv_area_t a;
a.x1 = coords->x1 + lv_area_get_width(coords) / 2 - size.x / 2;
a.x2 = a.x1 + size.x - 1;
a.y1 = coords->y1 + lv_area_get_height(coords) / 2 - size.y / 2;
a.y2 = a.y1 + size.y - 1;
lv_draw_label_dsc_t label_draw_dsc;
lv_draw_label_dsc_init(&label_draw_dsc);
label_draw_dsc.font = dsc->font;
label_draw_dsc.color = dsc->recolor;
label_draw_dsc.opa = dsc->opa;
label_draw_dsc.text = dsc->src;
lv_draw_sw_label(draw_unit, &label_draw_dsc, &a);
}
else {
lv_draw_image_dsc_t img_dsc;
lv_draw_image_dsc_init(&img_dsc);
img_dsc.recolor = dsc->recolor;
img_dsc.recolor_opa = dsc->recolor_opa;
img_dsc.opa = dsc->opa;
img_dsc.src = dsc->src;
/*Center align*/
if(dsc->tiled == false) {
lv_area_t area;
area.x1 = coords->x1 + lv_area_get_width(coords) / 2 - dsc->img_header.w / 2;
area.y1 = coords->y1 + lv_area_get_height(coords) / 2 - dsc->img_header.h / 2;
area.x2 = area.x1 + dsc->img_header.w - 1;
area.y2 = area.y1 + dsc->img_header.h - 1;
lv_draw_sw_image(draw_unit, &img_dsc, &area);
}
else {
lv_area_t area;
area.y1 = coords->y1;
area.y2 = area.y1 + dsc->img_header.h - 1;
for(; area.y1 <= coords->y2; area.y1 += dsc->img_header.h, area.y2 += dsc->img_header.h) {
area.x1 = coords->x1;
area.x2 = area.x1 + dsc->img_header.w - 1;
for(; area.x1 <= coords->x2; area.x1 += dsc->img_header.w, area.x2 += dsc->img_header.w) {
lv_draw_sw_image(draw_unit, &img_dsc, &area);
}
}
}
}
draw_unit->clip_area = clip_area_ori;
}
/**********************
* STATIC FUNCTIONS
**********************/
#endif /*LV_USE_DRAW_SW*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_box_shadow.c | /**
* @file lv_draw_sw_box_shadow.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_draw_sw.h"
#if LV_USE_DRAW_SW
#include "blend/lv_draw_sw_blend.h"
#include "../../core/lv_global.h"
#include "../../misc/lv_math.h"
#include "../../core/lv_refr.h"
#include "../../misc/lv_assert.h"
#include "../../stdlib/lv_string.h"
#include "../lv_draw_mask.h"
/*********************
* DEFINES
*********************/
#define SHADOW_UPSCALE_SHIFT 6
#define SHADOW_ENHANCE 1
#if defined(LV_DRAW_SW_SHADOW_CACHE_SIZE) && LV_DRAW_SW_SHADOW_CACHE_SIZE > 0
#define shadow_cache LV_GLOBAL_DEFAULT()->sw_shadow_cache
#endif
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
#if LV_DRAW_SW_COMPLEX
LV_ATTRIBUTE_FAST_MEM static void shadow_draw_corner_buf(const lv_area_t * coords, uint16_t * sh_buf, int32_t s,
int32_t r);
LV_ATTRIBUTE_FAST_MEM static void shadow_blur_corner(int32_t size, int32_t sw, uint16_t * sh_ups_buf);
#endif /*LV_DRAW_SW_COMPLEX*/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_sw_box_shadow(lv_draw_unit_t * draw_unit, const lv_draw_box_shadow_dsc_t * dsc, const lv_area_t * coords)
{
/*Calculate the rectangle which is blurred to get the shadow in `shadow_area`*/
lv_area_t core_area;
core_area.x1 = coords->x1 + dsc->ofs_x - dsc->spread;
core_area.x2 = coords->x2 + dsc->ofs_x + dsc->spread;
core_area.y1 = coords->y1 + dsc->ofs_y - dsc->spread;
core_area.y2 = coords->y2 + dsc->ofs_y + dsc->spread;
/*Calculate the bounding box of the shadow*/
lv_area_t shadow_area;
shadow_area.x1 = core_area.x1 - dsc->width / 2 - 1;
shadow_area.x2 = core_area.x2 + dsc->width / 2 + 1;
shadow_area.y1 = core_area.y1 - dsc->width / 2 - 1;
shadow_area.y2 = core_area.y2 + dsc->width / 2 + 1;
lv_opa_t opa = dsc->opa;
if(opa > LV_OPA_MAX) opa = LV_OPA_COVER;
/*Get clipped draw area which is the real draw area.
*It is always the same or inside `shadow_area`*/
lv_area_t draw_area;
if(!_lv_area_intersect(&draw_area, &shadow_area, draw_unit->clip_area)) return;
/*Consider 1 px smaller bg to be sure the edge will be covered by the shadow*/
lv_area_t bg_area;
lv_area_copy(&bg_area, coords);
lv_area_increase(&bg_area, -1, -1);
/*Get the clamped radius*/
int32_t r_bg = dsc->radius;
int32_t short_side = LV_MIN(lv_area_get_width(&bg_area), lv_area_get_height(&bg_area));
if(r_bg > short_side >> 1) r_bg = short_side >> 1;
/*Get the clamped radius*/
int32_t r_sh = dsc->radius;
short_side = LV_MIN(lv_area_get_width(&core_area), lv_area_get_height(&core_area));
if(r_sh > short_side >> 1) r_sh = short_side >> 1;
/*Get how many pixels are affected by the blur on the corners*/
int32_t corner_size = dsc->width + r_sh;
lv_opa_t * sh_buf;
#if LV_DRAW_SW_SHADOW_CACHE_SIZE
lv_draw_sw_shadow_cache_t * cache = &shadow_cache;
if(cache->cache_size == corner_size && cache->cache_r == r_sh) {
/*Use the cache if available*/
sh_buf = lv_malloc(corner_size * corner_size);
lv_memcpy(sh_buf, cache->cache, corner_size * corner_size);
}
else {
/*A larger buffer is required for calculation*/
sh_buf = lv_malloc(corner_size * corner_size * sizeof(uint16_t));
shadow_draw_corner_buf(&core_area, (uint16_t *)sh_buf, dsc->width, r_sh);
/*Cache the corner if it fits into the cache size*/
if((uint32_t)corner_size * corner_size < sizeof(cache->cache)) {
lv_memcpy(cache->cache, sh_buf, corner_size * corner_size);
cache->cache_size = corner_size;
cache->cache_r = r_sh;
}
}
#else
sh_buf = lv_malloc(corner_size * corner_size * sizeof(uint16_t));
shadow_draw_corner_buf(&core_area, (uint16_t *)sh_buf, dsc->width, r_sh);
#endif /*LV_DRAW_SW_SHADOW_CACHE_SIZE*/
/*Skip a lot of masking if the background will cover the shadow that would be masked out*/
bool simple = dsc->bg_cover;
/*Create a radius mask to clip remove shadow on the bg area*/
lv_draw_sw_mask_radius_param_t mask_rout_param;
void * masks[2] = {0};
if(!simple) {
lv_draw_sw_mask_radius_init(&mask_rout_param, &bg_area, r_bg, true);
masks[0] = &mask_rout_param;
}
lv_opa_t * mask_buf = lv_malloc(lv_area_get_width(&shadow_area));
lv_area_t blend_area;
lv_area_t clip_area_sub;
lv_opa_t * sh_buf_tmp;
int32_t y;
bool simple_sub;
lv_draw_sw_blend_dsc_t blend_dsc;
lv_memzero(&blend_dsc, sizeof(blend_dsc));
blend_dsc.blend_area = &blend_area;
blend_dsc.mask_area = &blend_area;
blend_dsc.mask_buf = mask_buf;
blend_dsc.color = dsc->color;
blend_dsc.opa = dsc->opa;
int32_t w_half = shadow_area.x1 + lv_area_get_width(&shadow_area) / 2;
int32_t h_half = shadow_area.y1 + lv_area_get_height(&shadow_area) / 2;
/*Draw the corners if they are on the current clip area and not fully covered by the bg*/
/*Top right corner*/
blend_area.x2 = shadow_area.x2;
blend_area.x1 = shadow_area.x2 - corner_size + 1;
blend_area.y1 = shadow_area.y1;
blend_area.y2 = shadow_area.y1 + corner_size - 1;
/*Do not overdraw the other top corners*/
blend_area.x1 = LV_MAX(blend_area.x1, w_half);
blend_area.y2 = LV_MIN(blend_area.y2, h_half);
if(_lv_area_intersect(&clip_area_sub, &blend_area, draw_unit->clip_area) &&
!_lv_area_is_in(&clip_area_sub, &bg_area, r_bg)) {
int32_t w = lv_area_get_width(&clip_area_sub);
sh_buf_tmp = sh_buf;
sh_buf_tmp += (clip_area_sub.y1 - shadow_area.y1) * corner_size;
sh_buf_tmp += clip_area_sub.x1 - (shadow_area.x2 - corner_size + 1);
/*Do not mask if out of the bg*/
if(simple && _lv_area_is_out(&clip_area_sub, &bg_area, r_bg)) simple_sub = true;
else simple_sub = simple;
if(w > 0) {
blend_dsc.mask_buf = mask_buf;
blend_area.x1 = clip_area_sub.x1;
blend_area.x2 = clip_area_sub.x2;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED; /*In simple mode it won't be overwritten*/
for(y = clip_area_sub.y1; y <= clip_area_sub.y2; y++) {
blend_area.y1 = y;
blend_area.y2 = y;
if(!simple_sub) {
lv_memcpy(mask_buf, sh_buf_tmp, corner_size);
blend_dsc.mask_res = lv_draw_sw_mask_apply(masks, mask_buf, clip_area_sub.x1, y, w);
if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_FULL_COVER) blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
}
else {
blend_dsc.mask_buf = sh_buf_tmp;
}
lv_draw_sw_blend(draw_unit, &blend_dsc);
sh_buf_tmp += corner_size;
}
}
}
/*Bottom right corner.
*Almost the same as top right just read the lines of `sh_buf` from then end*/
blend_area.x2 = shadow_area.x2;
blend_area.x1 = shadow_area.x2 - corner_size + 1;
blend_area.y1 = shadow_area.y2 - corner_size + 1;
blend_area.y2 = shadow_area.y2;
/*Do not overdraw the other corners*/
blend_area.x1 = LV_MAX(blend_area.x1, w_half);
blend_area.y1 = LV_MAX(blend_area.y1, h_half + 1);
if(_lv_area_intersect(&clip_area_sub, &blend_area, draw_unit->clip_area) &&
!_lv_area_is_in(&clip_area_sub, &bg_area, r_bg)) {
int32_t w = lv_area_get_width(&clip_area_sub);
sh_buf_tmp = sh_buf;
sh_buf_tmp += (blend_area.y2 - clip_area_sub.y2) * corner_size;
sh_buf_tmp += clip_area_sub.x1 - (shadow_area.x2 - corner_size + 1);
/*Do not mask if out of the bg*/
if(simple && _lv_area_is_out(&clip_area_sub, &bg_area, r_bg)) simple_sub = true;
else simple_sub = simple;
if(w > 0) {
blend_dsc.mask_buf = mask_buf;
blend_area.x1 = clip_area_sub.x1;
blend_area.x2 = clip_area_sub.x2;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED; /*In simple mode it won't be overwritten*/
for(y = clip_area_sub.y2; y >= clip_area_sub.y1; y--) {
blend_area.y1 = y;
blend_area.y2 = y;
if(!simple_sub) {
lv_memcpy(mask_buf, sh_buf_tmp, corner_size);
blend_dsc.mask_res = lv_draw_sw_mask_apply(masks, mask_buf, clip_area_sub.x1, y, w);
if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_FULL_COVER) blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
}
else {
blend_dsc.mask_buf = sh_buf_tmp;
}
lv_draw_sw_blend(draw_unit, &blend_dsc);
sh_buf_tmp += corner_size;
}
}
}
/*Top side*/
blend_area.x1 = shadow_area.x1 + corner_size;
blend_area.x2 = shadow_area.x2 - corner_size;
blend_area.y1 = shadow_area.y1;
blend_area.y2 = shadow_area.y1 + corner_size - 1;
blend_area.y2 = LV_MIN(blend_area.y2, h_half);
if(_lv_area_intersect(&clip_area_sub, &blend_area, draw_unit->clip_area) &&
!_lv_area_is_in(&clip_area_sub, &bg_area, r_bg)) {
int32_t w = lv_area_get_width(&clip_area_sub);
sh_buf_tmp = sh_buf;
sh_buf_tmp += (clip_area_sub.y1 - blend_area.y1) * corner_size;
/*Do not mask if out of the bg*/
if(simple && _lv_area_is_out(&clip_area_sub, &bg_area, r_bg)) simple_sub = true;
else simple_sub = simple;
if(w > 0) {
if(!simple_sub) {
blend_dsc.mask_buf = mask_buf;
}
else {
blend_dsc.mask_buf = NULL;
}
blend_area.x1 = clip_area_sub.x1;
blend_area.x2 = clip_area_sub.x2;
for(y = clip_area_sub.y1; y <= clip_area_sub.y2; y++) {
blend_area.y1 = y;
blend_area.y2 = y;
if(!simple_sub) {
lv_memset(mask_buf, sh_buf_tmp[0], w);
blend_dsc.mask_res = lv_draw_sw_mask_apply(masks, mask_buf, clip_area_sub.x1, y, w);
if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_FULL_COVER) blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
else {
blend_dsc.opa = opa == LV_OPA_COVER ? sh_buf_tmp[0] : LV_OPA_MIX2(sh_buf_tmp[0], dsc->opa);
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
sh_buf_tmp += corner_size;
}
}
}
blend_dsc.opa = dsc->opa; /*Restore*/
/*Bottom side*/
blend_area.x1 = shadow_area.x1 + corner_size;
blend_area.x2 = shadow_area.x2 - corner_size;
blend_area.y1 = shadow_area.y2 - corner_size + 1;
blend_area.y2 = shadow_area.y2;
blend_area.y1 = LV_MAX(blend_area.y1, h_half + 1);
if(_lv_area_intersect(&clip_area_sub, &blend_area, draw_unit->clip_area) &&
!_lv_area_is_in(&clip_area_sub, &bg_area, r_bg)) {
int32_t w = lv_area_get_width(&clip_area_sub);
sh_buf_tmp = sh_buf;
sh_buf_tmp += (blend_area.y2 - clip_area_sub.y2) * corner_size;
if(w > 0) {
/*Do not mask if out of the bg*/
if(simple && _lv_area_is_out(&clip_area_sub, &bg_area, r_bg)) simple_sub = true;
else simple_sub = simple;
if(!simple_sub) {
blend_dsc.mask_buf = mask_buf;
}
else {
blend_dsc.mask_buf = NULL;
}
blend_area.x1 = clip_area_sub.x1;
blend_area.x2 = clip_area_sub.x2;
for(y = clip_area_sub.y2; y >= clip_area_sub.y1; y--) {
blend_area.y1 = y;
blend_area.y2 = y;
/*Do not mask if out of the bg*/
if(simple && _lv_area_is_out(&clip_area_sub, &bg_area, r_bg)) simple_sub = true;
else simple_sub = simple;
if(!simple_sub) {
lv_memset(mask_buf, sh_buf_tmp[0], w);
blend_dsc.mask_res = lv_draw_sw_mask_apply(masks, mask_buf, clip_area_sub.x1, y, w);
if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_FULL_COVER) blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
else {
blend_dsc.opa = opa == LV_OPA_COVER ? sh_buf_tmp[0] : (sh_buf_tmp[0] * dsc->opa) >> 8;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
sh_buf_tmp += corner_size;
}
}
}
blend_dsc.opa = dsc->opa; /*Restore*/
/*Right side*/
blend_area.x1 = shadow_area.x2 - corner_size + 1;
blend_area.x2 = shadow_area.x2;
blend_area.y1 = shadow_area.y1 + corner_size;
blend_area.y2 = shadow_area.y2 - corner_size;
/*Do not overdraw the other corners*/
blend_area.y1 = LV_MIN(blend_area.y1, h_half + 1);
blend_area.y2 = LV_MAX(blend_area.y2, h_half);
blend_area.x1 = LV_MAX(blend_area.x1, w_half);
if(_lv_area_intersect(&clip_area_sub, &blend_area, draw_unit->clip_area) &&
!_lv_area_is_in(&clip_area_sub, &bg_area, r_bg)) {
int32_t w = lv_area_get_width(&clip_area_sub);
sh_buf_tmp = sh_buf;
sh_buf_tmp += (corner_size - 1) * corner_size;
sh_buf_tmp += clip_area_sub.x1 - (shadow_area.x2 - corner_size + 1);
/*Do not mask if out of the bg*/
if(simple && _lv_area_is_out(&clip_area_sub, &bg_area, r_bg)) simple_sub = true;
else simple_sub = simple;
blend_dsc.mask_buf = simple_sub ? sh_buf_tmp : mask_buf;
if(w > 0) {
blend_area.x1 = clip_area_sub.x1;
blend_area.x2 = clip_area_sub.x2;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED; /*In simple mode it won't be overwritten*/
for(y = clip_area_sub.y1; y <= clip_area_sub.y2; y++) {
blend_area.y1 = y;
blend_area.y2 = y;
if(!simple_sub) {
lv_memcpy(mask_buf, sh_buf_tmp, w);
blend_dsc.mask_res = lv_draw_sw_mask_apply(masks, mask_buf, clip_area_sub.x1, y, w);
if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_FULL_COVER) blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
}
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
}
}
/*Mirror the shadow corner buffer horizontally*/
sh_buf_tmp = sh_buf ;
for(y = 0; y < corner_size; y++) {
int32_t x;
lv_opa_t * start = sh_buf_tmp;
lv_opa_t * end = sh_buf_tmp + corner_size - 1;
for(x = 0; x < corner_size / 2; x++) {
lv_opa_t tmp = *start;
*start = *end;
*end = tmp;
start++;
end--;
}
sh_buf_tmp += corner_size;
}
/*Left side*/
blend_area.x1 = shadow_area.x1;
blend_area.x2 = shadow_area.x1 + corner_size - 1;
blend_area.y1 = shadow_area.y1 + corner_size;
blend_area.y2 = shadow_area.y2 - corner_size;
/*Do not overdraw the other corners*/
blend_area.y1 = LV_MIN(blend_area.y1, h_half + 1);
blend_area.y2 = LV_MAX(blend_area.y2, h_half);
blend_area.x2 = LV_MIN(blend_area.x2, w_half - 1);
if(_lv_area_intersect(&clip_area_sub, &blend_area, draw_unit->clip_area) &&
!_lv_area_is_in(&clip_area_sub, &bg_area, r_bg)) {
int32_t w = lv_area_get_width(&clip_area_sub);
sh_buf_tmp = sh_buf;
sh_buf_tmp += (corner_size - 1) * corner_size;
sh_buf_tmp += clip_area_sub.x1 - blend_area.x1;
/*Do not mask if out of the bg*/
if(simple && _lv_area_is_out(&clip_area_sub, &bg_area, r_bg)) simple_sub = true;
else simple_sub = simple;
blend_dsc.mask_buf = simple_sub ? sh_buf_tmp : mask_buf;
if(w > 0) {
blend_area.x1 = clip_area_sub.x1;
blend_area.x2 = clip_area_sub.x2;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED; /*In simple mode it won't be overwritten*/
for(y = clip_area_sub.y1; y <= clip_area_sub.y2; y++) {
blend_area.y1 = y;
blend_area.y2 = y;
if(!simple_sub) {
lv_memcpy(mask_buf, sh_buf_tmp, w);
blend_dsc.mask_res = lv_draw_sw_mask_apply(masks, mask_buf, clip_area_sub.x1, y, w);
if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_FULL_COVER) blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
}
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
}
}
/*Top left corner*/
blend_area.x1 = shadow_area.x1;
blend_area.x2 = shadow_area.x1 + corner_size - 1;
blend_area.y1 = shadow_area.y1;
blend_area.y2 = shadow_area.y1 + corner_size - 1;
/*Do not overdraw the other corners*/
blend_area.x2 = LV_MIN(blend_area.x2, w_half - 1);
blend_area.y2 = LV_MIN(blend_area.y2, h_half);
if(_lv_area_intersect(&clip_area_sub, &blend_area, draw_unit->clip_area) &&
!_lv_area_is_in(&clip_area_sub, &bg_area, r_bg)) {
int32_t w = lv_area_get_width(&clip_area_sub);
sh_buf_tmp = sh_buf;
sh_buf_tmp += (clip_area_sub.y1 - blend_area.y1) * corner_size;
sh_buf_tmp += clip_area_sub.x1 - blend_area.x1;
/*Do not mask if out of the bg*/
if(simple && _lv_area_is_out(&clip_area_sub, &bg_area, r_bg)) simple_sub = true;
else simple_sub = simple;
blend_dsc.mask_buf = mask_buf;
if(w > 0) {
blend_area.x1 = clip_area_sub.x1;
blend_area.x2 = clip_area_sub.x2;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED; /*In simple mode it won't be overwritten*/
for(y = clip_area_sub.y1; y <= clip_area_sub.y2; y++) {
blend_area.y1 = y;
blend_area.y2 = y;
if(!simple_sub) {
lv_memcpy(mask_buf, sh_buf_tmp, corner_size);
blend_dsc.mask_res = lv_draw_sw_mask_apply(masks, mask_buf, clip_area_sub.x1, y, w);
if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_FULL_COVER) blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
}
else {
blend_dsc.mask_buf = sh_buf_tmp;
}
lv_draw_sw_blend(draw_unit, &blend_dsc);
sh_buf_tmp += corner_size;
}
}
}
/*Bottom left corner.
*Almost the same as bottom right just read the lines of `sh_buf` from then end*/
blend_area.x1 = shadow_area.x1 ;
blend_area.x2 = shadow_area.x1 + corner_size - 1;
blend_area.y1 = shadow_area.y2 - corner_size + 1;
blend_area.y2 = shadow_area.y2;
/*Do not overdraw the other corners*/
blend_area.y1 = LV_MAX(blend_area.y1, h_half + 1);
blend_area.x2 = LV_MIN(blend_area.x2, w_half - 1);
if(_lv_area_intersect(&clip_area_sub, &blend_area, draw_unit->clip_area) &&
!_lv_area_is_in(&clip_area_sub, &bg_area, r_bg)) {
int32_t w = lv_area_get_width(&clip_area_sub);
sh_buf_tmp = sh_buf;
sh_buf_tmp += (blend_area.y2 - clip_area_sub.y2) * corner_size;
sh_buf_tmp += clip_area_sub.x1 - blend_area.x1;
/*Do not mask if out of the bg*/
if(simple && _lv_area_is_out(&clip_area_sub, &bg_area, r_bg)) simple_sub = true;
else simple_sub = simple;
blend_dsc.mask_buf = mask_buf;
if(w > 0) {
blend_area.x1 = clip_area_sub.x1;
blend_area.x2 = clip_area_sub.x2;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED; /*In simple mode it won't be overwritten*/
for(y = clip_area_sub.y2; y >= clip_area_sub.y1; y--) {
blend_area.y1 = y;
blend_area.y2 = y;
if(!simple_sub) {
lv_memcpy(mask_buf, sh_buf_tmp, corner_size);
blend_dsc.mask_res = lv_draw_sw_mask_apply(masks, mask_buf, clip_area_sub.x1, y, w);
if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_FULL_COVER) blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
}
else {
blend_dsc.mask_buf = sh_buf_tmp;
}
lv_draw_sw_blend(draw_unit, &blend_dsc);
sh_buf_tmp += corner_size;
}
}
}
/*Draw the center rectangle.*/
blend_area.x1 = shadow_area.x1 + corner_size ;
blend_area.x2 = shadow_area.x2 - corner_size;
blend_area.y1 = shadow_area.y1 + corner_size;
blend_area.y2 = shadow_area.y2 - corner_size;
blend_dsc.mask_buf = mask_buf;
if(_lv_area_intersect(&clip_area_sub, &blend_area, draw_unit->clip_area) &&
!_lv_area_is_in(&clip_area_sub, &bg_area, r_bg)) {
int32_t w = lv_area_get_width(&clip_area_sub);
if(w > 0) {
blend_area.x1 = clip_area_sub.x1;
blend_area.x2 = clip_area_sub.x2;
for(y = clip_area_sub.y1; y <= clip_area_sub.y2; y++) {
blend_area.y1 = y;
blend_area.y2 = y;
lv_memset(mask_buf, 0xff, w);
blend_dsc.mask_res = lv_draw_sw_mask_apply(masks, mask_buf, clip_area_sub.x1, y, w);
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
}
}
if(!simple) {
lv_draw_sw_mask_free_param(&mask_rout_param);
}
lv_free(sh_buf);
lv_free(mask_buf);
}
#endif /*LV_USE_DRAW_SW*/
/**********************
* STATIC FUNCTIONS
**********************/
#if LV_DRAW_SW_COMPLEX
/**
* Calculate a blurred corner
* @param coords Coordinates of the shadow
* @param sh_buf a buffer to store the result. Its size should be `(sw + r)^2 * 2`
* @param sw shadow width
* @param r radius
*/
LV_ATTRIBUTE_FAST_MEM static void shadow_draw_corner_buf(const lv_area_t * coords, uint16_t * sh_buf, int32_t sw,
int32_t r)
{
int32_t sw_ori = sw;
int32_t size = sw_ori + r;
lv_area_t sh_area;
lv_area_copy(&sh_area, coords);
sh_area.x2 = sw / 2 + r - 1 - ((sw & 1) ? 0 : 1);
sh_area.y1 = sw / 2 + 1;
sh_area.x1 = sh_area.x2 - lv_area_get_width(coords);
sh_area.y2 = sh_area.y1 + lv_area_get_height(coords);
lv_draw_sw_mask_radius_param_t mask_param;
lv_draw_sw_mask_radius_init(&mask_param, &sh_area, r, false);
#if SHADOW_ENHANCE
/*Set half shadow width width because blur will be repeated*/
if(sw_ori == 1) sw = 1;
else sw = sw_ori >> 1;
#endif /*SHADOW_ENHANCE*/
int32_t y;
lv_opa_t * mask_line = lv_malloc(size);
uint16_t * sh_ups_tmp_buf = (uint16_t *)sh_buf;
for(y = 0; y < size; y++) {
lv_memset(mask_line, 0xff, size);
lv_draw_sw_mask_res_t mask_res = mask_param.dsc.cb(mask_line, 0, y, size, &mask_param);
if(mask_res == LV_DRAW_SW_MASK_RES_TRANSP) {
lv_memzero(sh_ups_tmp_buf, size * sizeof(sh_ups_tmp_buf[0]));
}
else {
int32_t i;
sh_ups_tmp_buf[0] = (mask_line[0] << SHADOW_UPSCALE_SHIFT) / sw;
for(i = 1; i < size; i++) {
if(mask_line[i] == mask_line[i - 1]) sh_ups_tmp_buf[i] = sh_ups_tmp_buf[i - 1];
else sh_ups_tmp_buf[i] = (mask_line[i] << SHADOW_UPSCALE_SHIFT) / sw;
}
}
sh_ups_tmp_buf += size;
}
lv_free(mask_line);
lv_draw_sw_mask_free_param(&mask_param);
if(sw == 1) {
int32_t i;
lv_opa_t * res_buf = (lv_opa_t *)sh_buf;
for(i = 0; i < size * size; i++) {
res_buf[i] = (sh_buf[i] >> SHADOW_UPSCALE_SHIFT);
}
return;
}
shadow_blur_corner(size, sw, sh_buf);
#if SHADOW_ENHANCE == 0
/*The result is required in lv_opa_t not uint16_t*/
uint32_t x;
lv_opa_t * res_buf = (lv_opa_t *)sh_buf;
for(x = 0; x < size * size; x++) {
res_buf[x] = sh_buf[x];
}
#else
sw += sw_ori & 1;
if(sw > 1) {
uint32_t i;
uint32_t max_v_div = (LV_OPA_COVER << SHADOW_UPSCALE_SHIFT) / sw;
for(i = 0; i < (uint32_t)size * size; i++) {
if(sh_buf[i] == 0) continue;
else if(sh_buf[i] == LV_OPA_COVER) sh_buf[i] = max_v_div;
else sh_buf[i] = (sh_buf[i] << SHADOW_UPSCALE_SHIFT) / sw;
}
shadow_blur_corner(size, sw, sh_buf);
}
int32_t x;
lv_opa_t * res_buf = (lv_opa_t *)sh_buf;
for(x = 0; x < size * size; x++) {
res_buf[x] = sh_buf[x];
}
#endif
}
LV_ATTRIBUTE_FAST_MEM static void shadow_blur_corner(int32_t size, int32_t sw, uint16_t * sh_ups_buf)
{
int32_t s_left = sw >> 1;
int32_t s_right = (sw >> 1);
if((sw & 1) == 0) s_left--;
/*Horizontal blur*/
uint16_t * sh_ups_blur_buf = lv_malloc(size * sizeof(uint16_t));
int32_t x;
int32_t y;
uint16_t * sh_ups_tmp_buf = sh_ups_buf;
for(y = 0; y < size; y++) {
int32_t v = sh_ups_tmp_buf[size - 1] * sw;
for(x = size - 1; x >= 0; x--) {
sh_ups_blur_buf[x] = v;
/*Forget the right pixel*/
uint32_t right_val = 0;
if(x + s_right < size) right_val = sh_ups_tmp_buf[x + s_right];
v -= right_val;
/*Add the left pixel*/
uint32_t left_val;
if(x - s_left - 1 < 0) left_val = sh_ups_tmp_buf[0];
else left_val = sh_ups_tmp_buf[x - s_left - 1];
v += left_val;
}
lv_memcpy(sh_ups_tmp_buf, sh_ups_blur_buf, size * sizeof(uint16_t));
sh_ups_tmp_buf += size;
}
/*Vertical blur*/
uint32_t i;
uint32_t max_v = LV_OPA_COVER << SHADOW_UPSCALE_SHIFT;
uint32_t max_v_div = max_v / sw;
for(i = 0; i < (uint32_t)size * size; i++) {
if(sh_ups_buf[i] == 0) continue;
else if(sh_ups_buf[i] == max_v) sh_ups_buf[i] = max_v_div;
else sh_ups_buf[i] = sh_ups_buf[i] / sw;
}
for(x = 0; x < size; x++) {
sh_ups_tmp_buf = &sh_ups_buf[x];
int32_t v = sh_ups_tmp_buf[0] * sw;
for(y = 0; y < size ; y++, sh_ups_tmp_buf += size) {
sh_ups_blur_buf[y] = v < 0 ? 0 : (v >> SHADOW_UPSCALE_SHIFT);
/*Forget the top pixel*/
uint32_t top_val;
if(y - s_right <= 0) top_val = sh_ups_tmp_buf[0];
else top_val = sh_ups_buf[(y - s_right) * size + x];
v -= top_val;
/*Add the bottom pixel*/
uint32_t bottom_val;
if(y + s_left + 1 < size) bottom_val = sh_ups_buf[(y + s_left + 1) * size + x];
else bottom_val = sh_ups_buf[(size - 1) * size + x];
v += bottom_val;
}
/*Write back the result into `sh_ups_buf`*/
sh_ups_tmp_buf = &sh_ups_buf[x];
for(y = 0; y < size; y++, sh_ups_tmp_buf += size) {
(*sh_ups_tmp_buf) = sh_ups_blur_buf[y];
}
}
lv_free(sh_ups_blur_buf);
}
#endif /*LV_DRAW_SW_COMPLEX*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw.c | /**
* @file lv_draw_sw.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../lv_draw.h"
#if LV_USE_DRAW_SW
#include "../../core/lv_refr.h"
#include "lv_draw_sw.h"
#include "../../display/lv_display_private.h"
#include "../../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
#define DRAW_UNIT_ID_SW 1
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
#if LV_USE_OS
static void render_thread_cb(void * ptr);
#endif
static void execute_drawing(lv_draw_sw_unit_t * u);
static int32_t lv_draw_sw_dispatch(lv_draw_unit_t * draw_unit, lv_layer_t * layer);
/**********************
* GLOBAL PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_sw_init(void)
{
#if LV_DRAW_SW_COMPLEX == 1
lv_draw_sw_mask_init();
#endif
uint32_t i;
for(i = 0; i < LV_DRAW_SW_DRAW_UNIT_CNT; i++) {
lv_draw_sw_unit_t * draw_sw_unit = lv_draw_create_unit(sizeof(lv_draw_sw_unit_t));
draw_sw_unit->base_unit.dispatch_cb = lv_draw_sw_dispatch;
draw_sw_unit->idx = i;
#if LV_USE_OS
lv_thread_init(&draw_sw_unit->thread, LV_THREAD_PRIO_HIGH, render_thread_cb, 8 * 1024, draw_sw_unit);
#endif
}
}
/**********************
* STATIC FUNCTIONS
**********************/
static int32_t lv_draw_sw_dispatch(lv_draw_unit_t * draw_unit, lv_layer_t * layer)
{
lv_draw_sw_unit_t * draw_sw_unit = (lv_draw_sw_unit_t *) draw_unit;
/*Return immediately if it's busy with draw task*/
if(draw_sw_unit->task_act) return 0;
lv_draw_task_t * t = NULL;
t = lv_draw_get_next_available_task(layer, NULL, DRAW_UNIT_ID_SW);
if(t == NULL) return -1;
void * buf = lv_draw_layer_alloc_buf(layer);
if(buf == NULL) return -1;
t->state = LV_DRAW_TASK_STATE_IN_PROGRESS;
draw_sw_unit->base_unit.target_layer = layer;
draw_sw_unit->base_unit.clip_area = &t->clip_area;
draw_sw_unit->task_act = t;
#if LV_USE_OS
/*Let the render thread work*/
lv_thread_sync_signal(&draw_sw_unit->sync);
#else
execute_drawing(draw_sw_unit);
draw_sw_unit->task_act->state = LV_DRAW_TASK_STATE_READY;
draw_sw_unit->task_act = NULL;
/*The draw unit is free now. Request a new dispatching as it can get a new task*/
lv_draw_dispatch_request();
#endif
return 1;
}
#if LV_USE_OS
static void render_thread_cb(void * ptr)
{
lv_draw_sw_unit_t * u = ptr;
lv_thread_sync_init(&u->sync);
while(1) {
while(u->task_act == NULL) {
lv_thread_sync_wait(&u->sync);
}
execute_drawing(u);
/*Cleanup*/
u->task_act->state = LV_DRAW_TASK_STATE_READY;
u->task_act = NULL;
/*The draw unit is free now. Request a new dispatching as it can get a new task*/
lv_draw_dispatch_request();
}
}
#endif
static void execute_drawing(lv_draw_sw_unit_t * u)
{
/*Render the draw task*/
lv_draw_task_t * t = u->task_act;
switch(t->type) {
case LV_DRAW_TASK_TYPE_FILL:
lv_draw_sw_fill((lv_draw_unit_t *)u, t->draw_dsc, &t->area);
break;
case LV_DRAW_TASK_TYPE_BORDER:
lv_draw_sw_border((lv_draw_unit_t *)u, t->draw_dsc, &t->area);
break;
case LV_DRAW_TASK_TYPE_BOX_SHADOW:
lv_draw_sw_box_shadow((lv_draw_unit_t *)u, t->draw_dsc, &t->area);
break;
case LV_DRAW_TASK_TYPE_BG_IMG:
lv_draw_sw_bg_image((lv_draw_unit_t *)u, t->draw_dsc, &t->area);
break;
case LV_DRAW_TASK_TYPE_LABEL:
lv_draw_sw_label((lv_draw_unit_t *)u, t->draw_dsc, &t->area);
break;
case LV_DRAW_TASK_TYPE_IMAGE:
lv_draw_sw_image((lv_draw_unit_t *)u, t->draw_dsc, &t->area);
break;
case LV_DRAW_TASK_TYPE_ARC:
lv_draw_sw_arc((lv_draw_unit_t *)u, t->draw_dsc, &t->area);
break;
case LV_DRAW_TASK_TYPE_LINE:
lv_draw_sw_line((lv_draw_unit_t *)u, t->draw_dsc);
break;
case LV_DRAW_TASK_TYPE_TRIANGLE:
lv_draw_sw_triangle((lv_draw_unit_t *)u, t->draw_dsc);
break;
case LV_DRAW_TASK_TYPE_LAYER:
lv_draw_sw_layer((lv_draw_unit_t *)u, t->draw_dsc, &t->area);
break;
case LV_DRAW_TASK_TYPE_MASK_RECTANGLE:
lv_draw_sw_mask_rect((lv_draw_unit_t *)u, t->draw_dsc, &t->area);
break;
default:
break;
}
#if LV_USE_PARALLEL_DRAW_DEBUG
/*Layers manage it for themselves*/
if(t->type != LV_DRAW_TASK_TYPE_LAYER) {
lv_area_t draw_area;
if(!_lv_area_intersect(&draw_area, &t->area, u->base_unit.clip_area)) return;
int32_t idx = 0;
lv_display_t * disp = _lv_refr_get_disp_refreshing();
lv_draw_unit_t * draw_unit_tmp = disp->draw_unit_head;
while(draw_unit_tmp != (lv_draw_unit_t *)u) {
draw_unit_tmp = draw_unit_tmp->next;
idx++;
}
lv_draw_rect_dsc_t rect_dsc;
lv_draw_rect_dsc_init(&rect_dsc);
rect_dsc.bg_color = lv_palette_main(idx % _LV_PALETTE_LAST);
rect_dsc.border_color = rect_dsc.bg_color;
rect_dsc.bg_opa = LV_OPA_10;
rect_dsc.border_opa = LV_OPA_80;
rect_dsc.border_width = 1;
lv_draw_sw_fill((lv_draw_unit_t *)u, &rect_dsc, &draw_area);
lv_point_t txt_size;
lv_text_get_size(&txt_size, "W", LV_FONT_DEFAULT, 0, 0, 100, LV_TEXT_FLAG_NONE);
lv_area_t txt_area;
txt_area.x1 = draw_area.x1;
txt_area.y1 = draw_area.y1;
txt_area.x2 = draw_area.x1 + txt_size.x - 1;
txt_area.y2 = draw_area.y1 + txt_size.y - 1;
lv_draw_rect_dsc_init(&rect_dsc);
rect_dsc.bg_color = lv_color_white();
lv_draw_sw_fill((lv_draw_unit_t *)u, &rect_dsc, &txt_area);
char buf[8];
lv_snprintf(buf, sizeof(buf), "%d", idx);
lv_draw_label_dsc_t label_dsc;
lv_draw_label_dsc_init(&label_dsc);
label_dsc.color = lv_color_black();
label_dsc.text = buf;
lv_draw_sw_label((lv_draw_unit_t *)u, &label_dsc, &txt_area);
}
#endif
}
#endif /*LV_USE_DRAW_SW*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_gradient.h | /**
* @file lv_draw_sw_gradient.h
*
*/
#ifndef LV_DRAW_SW_GRADIENT_H
#define LV_DRAW_SW_GRADIENT_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../misc/lv_color.h"
#include "../../misc/lv_style.h"
#if LV_USE_DRAW_SW
/*********************
* DEFINES
*********************/
#if LV_GRADIENT_MAX_STOPS < 2
#error LVGL needs at least 2 stops for gradients. Please increase the LV_GRADIENT_MAX_STOPS
#endif
/**********************
* TYPEDEFS
**********************/
typedef lv_color_t lv_grad_color_t;
typedef struct _lv_gradient_cache_t {
lv_color_t * color_map;
lv_opa_t * opa_map;
uint32_t size;
} lv_grad_t;
/**********************
* PROTOTYPES
**********************/
/** Compute the color in the given gradient and fraction
* Gradient are specified in a virtual [0-255] range, so this function scales the virtual range to the given range
* @param dsc The gradient descriptor to use
* @param range The range to use in computation.
* @param frac The current part used in the range. frac is in [0; range]
*/
LV_ATTRIBUTE_FAST_MEM void lv_gradient_color_calculate(const lv_grad_dsc_t * dsc, int32_t range,
int32_t frac, lv_grad_color_t * color_out, lv_opa_t * opa_out);
/** Get a gradient cache from the given parameters */
lv_grad_t * lv_gradient_get(const lv_grad_dsc_t * gradient, int32_t w, int32_t h);
/**
* Clean up the gradient item after it was get with `lv_grad_get_from_cache`.
* @param grad pointer to a gradient
*/
void lv_gradient_cleanup(lv_grad_t * grad);
#endif /*LV_USE_DRAW_SW*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_GRADIENT_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_line.c | /**
* @file lv_draw_sw_line.c
*
*/
/*********************
* INCLUDES
*********************/
#include <stdbool.h>
#include "lv_draw_sw.h"
#if LV_USE_DRAW_SW
#include "../../misc/lv_math.h"
#include "../../core/lv_refr.h"
#include "../../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
LV_ATTRIBUTE_FAST_MEM static void draw_line_skew(lv_draw_unit_t * draw_unit, const lv_draw_line_dsc_t * dsc);
LV_ATTRIBUTE_FAST_MEM static void draw_line_hor(lv_draw_unit_t * draw_unit, const lv_draw_line_dsc_t * dsc);
LV_ATTRIBUTE_FAST_MEM static void draw_line_ver(lv_draw_unit_t * draw_unit, const lv_draw_line_dsc_t * dsc);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Draw a line
* @param point1 first point of the line
* @param point2 second point of the line
* @param clip the line will be drawn only in this area
* @param dsc pointer to an initialized `lv_draw_line_dsc_t` variable
*/
LV_ATTRIBUTE_FAST_MEM void lv_draw_sw_line(lv_draw_unit_t * draw_unit, const lv_draw_line_dsc_t * dsc)
{
if(dsc->width == 0) return;
if(dsc->opa <= LV_OPA_MIN) return;
if(dsc->p1_x == dsc->p2_x && dsc->p1_y == dsc->p2_y) return;
lv_area_t clip_line;
clip_line.x1 = (int32_t)LV_MIN(dsc->p1_x, dsc->p2_x) - dsc->width / 2;
clip_line.x2 = (int32_t)LV_MAX(dsc->p1_x, dsc->p2_x) + dsc->width / 2;
clip_line.y1 = (int32_t)LV_MIN(dsc->p1_y, dsc->p2_y) - dsc->width / 2;
clip_line.y2 = (int32_t)LV_MAX(dsc->p1_y, dsc->p2_y) + dsc->width / 2;
bool is_common;
is_common = _lv_area_intersect(&clip_line, &clip_line, draw_unit->clip_area);
if(!is_common) return;
if(dsc->p1_y == dsc->p2_y) draw_line_hor(draw_unit, dsc);
else if(dsc->p1_x == dsc->p2_x) draw_line_ver(draw_unit, dsc);
else draw_line_skew(draw_unit, dsc);
if(dsc->round_end || dsc->round_start) {
lv_draw_fill_dsc_t cir_dsc;
lv_draw_fill_dsc_init(&cir_dsc);
cir_dsc.color = dsc->color;
cir_dsc.radius = LV_RADIUS_CIRCLE;
cir_dsc.opa = dsc->opa;
int32_t r = (dsc->width >> 1);
int32_t r_corr = (dsc->width & 1) ? 0 : 1;
lv_area_t cir_area;
if(dsc->round_start) {
cir_area.x1 = (int32_t)dsc->p1_x - r;
cir_area.y1 = (int32_t)dsc->p1_y - r;
cir_area.x2 = (int32_t)dsc->p1_x + r - r_corr;
cir_area.y2 = (int32_t)dsc->p1_y + r - r_corr ;
lv_draw_sw_fill(draw_unit, &cir_dsc, &cir_area);
}
if(dsc->round_end) {
cir_area.x1 = (int32_t)dsc->p2_x - r;
cir_area.y1 = (int32_t)dsc->p2_y - r;
cir_area.x2 = (int32_t)dsc->p2_x + r - r_corr;
cir_area.y2 = (int32_t)dsc->p2_y + r - r_corr ;
lv_draw_sw_fill(draw_unit, &cir_dsc, &cir_area);
}
}
}
/**********************
* STATIC FUNCTIONS
**********************/
LV_ATTRIBUTE_FAST_MEM static void draw_line_hor(lv_draw_unit_t * draw_unit, const lv_draw_line_dsc_t * dsc)
{
int32_t w = dsc->width - 1;
int32_t w_half0 = w >> 1;
int32_t w_half1 = w_half0 + (w & 0x1); /*Compensate rounding error*/
lv_area_t blend_area;
blend_area.x1 = (int32_t)LV_MIN(dsc->p1_x, dsc->p2_x);
blend_area.x2 = (int32_t)LV_MAX(dsc->p1_x, dsc->p2_x) - 1;
blend_area.y1 = (int32_t)dsc->p1_y - w_half1;
blend_area.y2 = (int32_t)dsc->p1_y + w_half0;
bool is_common;
is_common = _lv_area_intersect(&blend_area, &blend_area, draw_unit->clip_area);
if(!is_common) return;
bool dashed = dsc->dash_gap && dsc->dash_width;
lv_draw_sw_blend_dsc_t blend_dsc;
lv_memzero(&blend_dsc, sizeof(blend_dsc));
blend_dsc.blend_area = &blend_area;
blend_dsc.color = dsc->color;
blend_dsc.opa = dsc->opa;
/*If there is no mask then simply draw a rectangle*/
if(!dashed) {
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
#if LV_DRAW_SW_COMPLEX
/*If there other mask apply it*/
else {
int32_t blend_area_w = lv_area_get_width(&blend_area);
int32_t y2 = blend_area.y2;
blend_area.y2 = blend_area.y1;
int32_t dash_start = blend_area.x1 % (dsc->dash_gap + dsc->dash_width);
lv_opa_t * mask_buf = lv_malloc(blend_area_w);
blend_dsc.mask_buf = mask_buf;
blend_dsc.mask_area = &blend_area;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
int32_t h;
for(h = blend_area.y1; h <= y2; h++) {
lv_memset(mask_buf, 0xff, blend_area_w);
int32_t dash_cnt = dash_start;
int32_t i;
for(i = 0; i < blend_area_w; i++, dash_cnt++) {
if(dash_cnt <= dsc->dash_width) {
int16_t diff = dsc->dash_width - dash_cnt;
i += diff;
dash_cnt += diff;
}
else if(dash_cnt >= dsc->dash_gap + dsc->dash_width) {
dash_cnt = 0;
}
else {
mask_buf[i] = 0x00;
}
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
}
lv_draw_sw_blend(draw_unit, &blend_dsc);
blend_area.y1++;
blend_area.y2++;
}
lv_free(mask_buf);
}
#endif /*LV_DRAW_SW_COMPLEX*/
}
LV_ATTRIBUTE_FAST_MEM static void draw_line_ver(lv_draw_unit_t * draw_unit, const lv_draw_line_dsc_t * dsc)
{
int32_t w = dsc->width - 1;
int32_t w_half0 = w >> 1;
int32_t w_half1 = w_half0 + (w & 0x1); /*Compensate rounding error*/
lv_area_t blend_area;
blend_area.x1 = (int32_t)dsc->p1_x - w_half1;
blend_area.x2 = (int32_t)dsc->p1_x + w_half0;
blend_area.y1 = (int32_t)LV_MIN(dsc->p1_y, dsc->p2_y);
blend_area.y2 = (int32_t)LV_MAX(dsc->p1_y, dsc->p2_y) - 1;
bool is_common;
is_common = _lv_area_intersect(&blend_area, &blend_area, draw_unit->clip_area);
if(!is_common) return;
bool dashed = dsc->dash_gap && dsc->dash_width;
lv_draw_sw_blend_dsc_t blend_dsc;
lv_memzero(&blend_dsc, sizeof(blend_dsc));
blend_dsc.blend_area = &blend_area;
blend_dsc.color = dsc->color;
blend_dsc.opa = dsc->opa;
/*If there is no mask then simply draw a rectangle*/
if(!dashed) {
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
#if LV_DRAW_SW_COMPLEX
/*If there other mask apply it*/
else {
int32_t draw_area_w = lv_area_get_width(&blend_area);
int32_t y2 = blend_area.y2;
blend_area.y2 = blend_area.y1;
lv_opa_t * mask_buf = lv_malloc(draw_area_w);
blend_dsc.mask_buf = mask_buf;
blend_dsc.mask_area = &blend_area;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
int32_t dash_start = (blend_area.y1) % (dsc->dash_gap + dsc->dash_width);
int32_t dash_cnt = dash_start;
int32_t h;
for(h = blend_area.y1; h <= y2; h++) {
lv_memset(mask_buf, 0xff, draw_area_w);
if(dash_cnt > dsc->dash_width) {
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_TRANSP;
}
else {
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_FULL_COVER;
}
if(dash_cnt >= dsc->dash_gap + dsc->dash_width) {
dash_cnt = 0;
}
dash_cnt ++;
lv_draw_sw_blend(draw_unit, &blend_dsc);
blend_area.y1++;
blend_area.y2++;
}
lv_free(mask_buf);
}
#endif /*LV_DRAW_SW_COMPLEX*/
}
LV_ATTRIBUTE_FAST_MEM static void draw_line_skew(lv_draw_unit_t * draw_unit, const lv_draw_line_dsc_t * dsc)
{
#if LV_DRAW_SW_COMPLEX
/*Keep the great y in p1*/
lv_point_t p1;
lv_point_t p2;
if(dsc->p1_y < dsc->p2_y) {
p1.y = (int32_t)dsc->p1_y;
p2.y = (int32_t)dsc->p2_y;
p1.x = (int32_t)dsc->p1_x;
p2.x = (int32_t)dsc->p2_x;
}
else {
p1.y = (int32_t)dsc->p2_y;
p2.y = (int32_t)dsc->p1_y;
p1.x = (int32_t)dsc->p2_x;
p2.x = (int32_t)dsc->p1_x;
}
int32_t xdiff = p2.x - p1.x;
int32_t ydiff = p2.y - p1.y;
bool flat = LV_ABS(xdiff) > LV_ABS(ydiff);
static const uint8_t wcorr[] = {
128, 128, 128, 129, 129, 130, 130, 131,
132, 133, 134, 135, 137, 138, 140, 141,
143, 145, 147, 149, 151, 153, 155, 158,
160, 162, 165, 167, 170, 173, 175, 178,
181,
};
int32_t w = dsc->width;
int32_t wcorr_i = 0;
if(flat) wcorr_i = (LV_ABS(ydiff) << 5) / LV_ABS(xdiff);
else wcorr_i = (LV_ABS(xdiff) << 5) / LV_ABS(ydiff);
w = (w * wcorr[wcorr_i] + 63) >> 7; /*+ 63 for rounding*/
int32_t w_half0 = w >> 1;
int32_t w_half1 = w_half0 + (w & 0x1); /*Compensate rounding error*/
lv_area_t blend_area;
blend_area.x1 = LV_MIN(p1.x, p2.x) - w;
blend_area.x2 = LV_MAX(p1.x, p2.x) + w;
blend_area.y1 = LV_MIN(p1.y, p2.y) - w;
blend_area.y2 = LV_MAX(p1.y, p2.y) + w;
/*Get the union of `coords` and `clip`*/
/*`clip` is already truncated to the `draw_buf` size
*in 'lv_refr_area' function*/
bool is_common = _lv_area_intersect(&blend_area, &blend_area, draw_unit->clip_area);
if(is_common == false) return;
lv_draw_sw_mask_line_param_t mask_left_param;
lv_draw_sw_mask_line_param_t mask_right_param;
lv_draw_sw_mask_line_param_t mask_top_param;
lv_draw_sw_mask_line_param_t mask_bottom_param;
void * masks[5] = {&mask_left_param, & mask_right_param, NULL, NULL, NULL};
if(flat) {
if(xdiff > 0) {
lv_draw_sw_mask_line_points_init(&mask_left_param, p1.x, p1.y - w_half0, p2.x, p2.y - w_half0,
LV_DRAW_SW_MASK_LINE_SIDE_LEFT);
lv_draw_sw_mask_line_points_init(&mask_right_param, p1.x, p1.y + w_half1, p2.x, p2.y + w_half1,
LV_DRAW_SW_MASK_LINE_SIDE_RIGHT);
}
else {
lv_draw_sw_mask_line_points_init(&mask_left_param, p1.x, p1.y + w_half1, p2.x, p2.y + w_half1,
LV_DRAW_SW_MASK_LINE_SIDE_LEFT);
lv_draw_sw_mask_line_points_init(&mask_right_param, p1.x, p1.y - w_half0, p2.x, p2.y - w_half0,
LV_DRAW_SW_MASK_LINE_SIDE_RIGHT);
}
}
else {
lv_draw_sw_mask_line_points_init(&mask_left_param, p1.x + w_half1, p1.y, p2.x + w_half1, p2.y,
LV_DRAW_SW_MASK_LINE_SIDE_LEFT);
lv_draw_sw_mask_line_points_init(&mask_right_param, p1.x - w_half0, p1.y, p2.x - w_half0, p2.y,
LV_DRAW_SW_MASK_LINE_SIDE_RIGHT);
}
/*Use the normal vector for the endings*/
if(!dsc->raw_end) {
lv_draw_sw_mask_line_points_init(&mask_top_param, p1.x, p1.y, p1.x - ydiff, p1.y + xdiff,
LV_DRAW_SW_MASK_LINE_SIDE_BOTTOM);
lv_draw_sw_mask_line_points_init(&mask_bottom_param, p2.x, p2.y, p2.x - ydiff, p2.y + xdiff,
LV_DRAW_SW_MASK_LINE_SIDE_TOP);
masks[2] = &mask_top_param;
masks[3] = &mask_bottom_param;
}
/*The real draw area is around the line.
*It's easy to calculate with steep lines, but the area can be very wide with very flat lines.
*So deal with it only with steep lines.*/
int32_t draw_area_w = lv_area_get_width(&blend_area);
/*Draw the background line by line*/
int32_t h;
uint32_t hor_res = (uint32_t)lv_display_get_horizontal_resolution(_lv_refr_get_disp_refreshing());
size_t mask_buf_size = LV_MIN(lv_area_get_size(&blend_area), hor_res);
lv_opa_t * mask_buf = lv_malloc(mask_buf_size);
int32_t y2 = blend_area.y2;
blend_area.y2 = blend_area.y1;
uint32_t mask_p = 0;
lv_memset(mask_buf, 0xff, mask_buf_size);
lv_draw_sw_blend_dsc_t blend_dsc;
lv_memzero(&blend_dsc, sizeof(blend_dsc));
blend_dsc.blend_area = &blend_area;
blend_dsc.color = dsc->color;
blend_dsc.opa = dsc->opa;
blend_dsc.mask_buf = mask_buf;
blend_dsc.mask_area = &blend_area;
/*Fill the first row with 'color'*/
for(h = blend_area.y1; h <= y2; h++) {
blend_dsc.mask_res = lv_draw_sw_mask_apply(masks, &mask_buf[mask_p], blend_area.x1, h, draw_area_w);
if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_TRANSP) {
lv_memzero(&mask_buf[mask_p], draw_area_w);
}
mask_p += draw_area_w;
if((uint32_t) mask_p + draw_area_w < mask_buf_size) {
blend_area.y2 ++;
}
else {
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
lv_draw_sw_blend(draw_unit, &blend_dsc);
blend_area.y1 = blend_area.y2 + 1;
blend_area.y2 = blend_area.y1;
mask_p = 0;
lv_memset(mask_buf, 0xff, mask_buf_size);
}
}
/*Flush the last part*/
if(blend_area.y1 != blend_area.y2) {
blend_area.y2--;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
lv_free(mask_buf);
lv_draw_sw_mask_free_param(&mask_left_param);
lv_draw_sw_mask_free_param(&mask_right_param);
if(!dsc->raw_end) {
lv_draw_sw_mask_free_param(&mask_top_param);
lv_draw_sw_mask_free_param(&mask_bottom_param);
}
#else
LV_UNUSED(draw_unit);
LV_UNUSED(dsc);
LV_LOG_WARN("Can't draw skewed line with LV_DRAW_SW_COMPLEX == 0");
#endif /*LV_DRAW_SW_COMPLEX*/
}
#endif /*LV_USE_DRAW_SW*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_mask.c | /**
* @file lv_draw_sw_mask.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../lv_draw.h"
#if LV_DRAW_SW_COMPLEX
#include "lv_draw_sw_mask.h"
#include "../../core/lv_global.h"
#include "../../misc/lv_math.h"
#include "../../misc/lv_log.h"
#include "../../misc/lv_assert.h"
#include "../../osal/lv_os.h"
#include "../../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
#define CIRCLE_CACHE_LIFE_MAX 1000
#define CIRCLE_CACHE_AGING(life, r) life = LV_MIN(life + (r < 16 ? 1 : (r >> 4)), 1000)
#define circle_cache_mutex LV_GLOBAL_DEFAULT()->draw_info.circle_cache_mutex
#define _circle_cache LV_GLOBAL_DEFAULT()->sw_circle_cache
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t lv_draw_mask_line(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y, int32_t len,
lv_draw_sw_mask_line_param_t * param);
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t lv_draw_mask_radius(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y, int32_t len,
lv_draw_sw_mask_radius_param_t * param);
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t lv_draw_mask_angle(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y, int32_t len,
lv_draw_sw_mask_angle_param_t * param);
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t lv_draw_mask_fade(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y, int32_t len,
lv_draw_sw_mask_fade_param_t * param);
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t lv_draw_mask_map(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y, int32_t len,
lv_draw_sw_mask_map_param_t * param);
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t line_mask_flat(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y,
int32_t len,
lv_draw_sw_mask_line_param_t * p);
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t line_mask_steep(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y,
int32_t len,
lv_draw_sw_mask_line_param_t * p);
static void circ_init(lv_point_t * c, int32_t * tmp, int32_t radius);
static bool circ_cont(lv_point_t * c);
static void circ_next(lv_point_t * c, int32_t * tmp);
static void circ_calc_aa4(_lv_draw_sw_mask_radius_circle_dsc_t * c, int32_t radius);
static lv_opa_t * get_next_line(_lv_draw_sw_mask_radius_circle_dsc_t * c, int32_t y, int32_t * len,
int32_t * x_start);
LV_ATTRIBUTE_FAST_MEM static inline lv_opa_t mask_mix(lv_opa_t mask_act, lv_opa_t mask_new);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_sw_mask_init(void)
{
lv_mutex_init(&circle_cache_mutex);
}
LV_ATTRIBUTE_FAST_MEM lv_draw_sw_mask_res_t lv_draw_sw_mask_apply(void * masks[], lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y,
int32_t len)
{
bool changed = false;
_lv_draw_sw_mask_common_dsc_t * dsc;
uint32_t i;
for(i = 0; masks[i]; i++) {
dsc = masks[i];
lv_draw_sw_mask_res_t res = LV_DRAW_SW_MASK_RES_FULL_COVER;
res = dsc->cb(mask_buf, abs_x, abs_y, len, masks[i]);
if(res == LV_DRAW_SW_MASK_RES_TRANSP) return LV_DRAW_SW_MASK_RES_TRANSP;
else if(res == LV_DRAW_SW_MASK_RES_CHANGED) changed = true;
}
return changed ? LV_DRAW_SW_MASK_RES_CHANGED : LV_DRAW_SW_MASK_RES_FULL_COVER;
}
/**
* Free the data from the parameter.
* It's called inside `lv_draw_mask_remove_id` and `lv_draw_mask_remove_custom`
* Needs to be called only in special cases when the mask is not added by `lv_draw_mask_add`
* and not removed by `lv_draw_mask_remove_id` or `lv_draw_mask_remove_custom`
* @param p pointer to a mask parameter
*/
void lv_draw_sw_mask_free_param(void * p)
{
lv_mutex_lock(&circle_cache_mutex);
_lv_draw_sw_mask_common_dsc_t * pdsc = p;
if(pdsc->type == LV_DRAW_SW_MASK_TYPE_RADIUS) {
lv_draw_sw_mask_radius_param_t * radius_p = (lv_draw_sw_mask_radius_param_t *) p;
if(radius_p->circle) {
if(radius_p->circle->life < 0) {
lv_free(radius_p->circle->cir_opa);
lv_free(radius_p->circle);
}
else {
radius_p->circle->used_cnt--;
}
}
}
lv_mutex_unlock(&circle_cache_mutex);
}
void _lv_draw_sw_mask_cleanup(void)
{
uint8_t i;
for(i = 0; i < LV_DRAW_SW_CIRCLE_CACHE_SIZE; i++) {
if(_circle_cache[i].buf) {
lv_free(_circle_cache[i].buf);
}
lv_memzero(&(_circle_cache[i]), sizeof(_circle_cache[i]));
}
}
/**
*Initialize a line mask from two points.
* @param param pointer to a `lv_draw_mask_param_t` to initialize
* @param p1x X coordinate of the first point of the line
* @param p1y Y coordinate of the first point of the line
* @param p2x X coordinate of the second point of the line
* @param p2y y coordinate of the second point of the line
* @param side and element of `lv_draw_mask_line_side_t` to describe which side to keep.
* With `LV_DRAW_SW_MASK_LINE_SIDE_LEFT/RIGHT` and horizontal line all pixels are kept
* With `LV_DRAW_SW_MASK_LINE_SIDE_TOP/BOTTOM` and vertical line all pixels are kept
*/
void lv_draw_sw_mask_line_points_init(lv_draw_sw_mask_line_param_t * param, int32_t p1x, int32_t p1y,
int32_t p2x,
int32_t p2y, lv_draw_sw_mask_line_side_t side)
{
lv_memzero(param, sizeof(lv_draw_sw_mask_line_param_t));
if(p1y == p2y && side == LV_DRAW_SW_MASK_LINE_SIDE_BOTTOM) {
p1y--;
p2y--;
}
if(p1y > p2y) {
int32_t t;
t = p2x;
p2x = p1x;
p1x = t;
t = p2y;
p2y = p1y;
p1y = t;
}
param->cfg.p1.x = p1x;
param->cfg.p1.y = p1y;
param->cfg.p2.x = p2x;
param->cfg.p2.y = p2y;
param->cfg.side = side;
param->origo.x = p1x;
param->origo.y = p1y;
param->flat = (LV_ABS(p2x - p1x) > LV_ABS(p2y - p1y)) ? 1 : 0;
param->yx_steep = 0;
param->xy_steep = 0;
param->dsc.cb = (lv_draw_sw_mask_xcb_t)lv_draw_mask_line;
param->dsc.type = LV_DRAW_SW_MASK_TYPE_LINE;
int32_t dx = p2x - p1x;
int32_t dy = p2y - p1y;
if(param->flat) {
/*Normalize the steep. Delta x should be relative to delta x = 1024*/
int32_t m;
if(dx) {
m = (1L << 20) / dx; /*m is multiplier to normalize y (upscaled by 1024)*/
param->yx_steep = (m * dy) >> 10;
}
if(dy) {
m = (1L << 20) / dy; /*m is multiplier to normalize x (upscaled by 1024)*/
param->xy_steep = (m * dx) >> 10;
}
param->steep = param->yx_steep;
}
else {
/*Normalize the steep. Delta y should be relative to delta x = 1024*/
int32_t m;
if(dy) {
m = (1L << 20) / dy; /*m is multiplier to normalize x (upscaled by 1024)*/
param->xy_steep = (m * dx) >> 10;
}
if(dx) {
m = (1L << 20) / dx; /*m is multiplier to normalize x (upscaled by 1024)*/
param->yx_steep = (m * dy) >> 10;
}
param->steep = param->xy_steep;
}
if(param->cfg.side == LV_DRAW_SW_MASK_LINE_SIDE_LEFT) param->inv = 0;
else if(param->cfg.side == LV_DRAW_SW_MASK_LINE_SIDE_RIGHT) param->inv = 1;
else if(param->cfg.side == LV_DRAW_SW_MASK_LINE_SIDE_TOP) {
if(param->steep > 0) param->inv = 1;
else param->inv = 0;
}
else if(param->cfg.side == LV_DRAW_SW_MASK_LINE_SIDE_BOTTOM) {
if(param->steep > 0) param->inv = 0;
else param->inv = 1;
}
param->spx = param->steep >> 2;
if(param->steep < 0) param->spx = -param->spx;
}
/**
*Initialize a line mask from a point and an angle.
* @param param pointer to a `lv_draw_mask_param_t` to initialize
* @param px X coordinate of a point of the line
* @param py X coordinate of a point of the line
* @param angle right 0 deg, bottom: 90
* @param side and element of `lv_draw_mask_line_side_t` to describe which side to keep.
* With `LV_DRAW_SW_MASK_LINE_SIDE_LEFT/RIGHT` and horizontal line all pixels are kept
* With `LV_DRAW_SW_MASK_LINE_SIDE_TOP/BOTTOM` and vertical line all pixels are kept
*/
void lv_draw_sw_mask_line_angle_init(lv_draw_sw_mask_line_param_t * param, int32_t p1x, int32_t py, int16_t angle,
lv_draw_sw_mask_line_side_t side)
{
/*Find an optimal degree.
*lv_mask_line_points_init will swap the points to keep the smaller y in p1
*Theoretically a line with `angle` or `angle+180` is the same only the points are swapped
*Find the degree which keeps the origo in place*/
if(angle > 180) angle -= 180; /*> 180 will swap the origo*/
int32_t p2x;
int32_t p2y;
p2x = (lv_trigo_sin(angle + 90) >> 5) + p1x;
p2y = (lv_trigo_sin(angle) >> 5) + py;
lv_draw_sw_mask_line_points_init(param, p1x, py, p2x, p2y, side);
}
/**
* Initialize an angle mask.
* @param param pointer to a `lv_draw_mask_param_t` to initialize
* @param vertex_x X coordinate of the angle vertex (absolute coordinates)
* @param vertex_y Y coordinate of the angle vertex (absolute coordinates)
* @param start_angle start angle in degrees. 0 deg on the right, 90 deg, on the bottom
* @param end_angle end angle
*/
void lv_draw_sw_mask_angle_init(lv_draw_sw_mask_angle_param_t * param, int32_t vertex_x, int32_t vertex_y,
int32_t start_angle, int32_t end_angle)
{
lv_draw_sw_mask_line_side_t start_side;
lv_draw_sw_mask_line_side_t end_side;
/*Constrain the input angles*/
if(start_angle < 0)
start_angle = 0;
else if(start_angle > 359)
start_angle = 359;
if(end_angle < 0)
end_angle = 0;
else if(end_angle > 359)
end_angle = 359;
if(end_angle < start_angle) {
param->delta_deg = 360 - start_angle + end_angle;
}
else {
param->delta_deg = LV_ABS(end_angle - start_angle);
}
param->cfg.start_angle = start_angle;
param->cfg.end_angle = end_angle;
param->cfg.vertex_p.x = vertex_x;
param->cfg.vertex_p.y = vertex_y;
param->dsc.cb = (lv_draw_sw_mask_xcb_t)lv_draw_mask_angle;
param->dsc.type = LV_DRAW_SW_MASK_TYPE_ANGLE;
LV_ASSERT_MSG(start_angle >= 0 && start_angle <= 360, "Unexpected start angle");
if(start_angle >= 0 && start_angle < 180) {
start_side = LV_DRAW_SW_MASK_LINE_SIDE_LEFT;
}
else
start_side = LV_DRAW_SW_MASK_LINE_SIDE_RIGHT; /*silence compiler*/
LV_ASSERT_MSG(end_angle >= 0 && start_angle <= 360, "Unexpected end angle");
if(end_angle >= 0 && end_angle < 180) {
end_side = LV_DRAW_SW_MASK_LINE_SIDE_RIGHT;
}
else if(end_angle >= 180 && end_angle < 360) {
end_side = LV_DRAW_SW_MASK_LINE_SIDE_LEFT;
}
else
end_side = LV_DRAW_SW_MASK_LINE_SIDE_RIGHT; /*silence compiler*/
lv_draw_sw_mask_line_angle_init(¶m->start_line, vertex_x, vertex_y, start_angle, start_side);
lv_draw_sw_mask_line_angle_init(¶m->end_line, vertex_x, vertex_y, end_angle, end_side);
}
/**
* Initialize a fade mask.
* @param param pointer to an `lv_draw_mask_radius_param_t` to initialize
* @param rect coordinates of the rectangle to affect (absolute coordinates)
* @param radius radius of the rectangle
* @param inv true: keep the pixels inside the rectangle; keep the pixels outside of the rectangle
*/
void lv_draw_sw_mask_radius_init(lv_draw_sw_mask_radius_param_t * param, const lv_area_t * rect, int32_t radius,
bool inv)
{
int32_t w = lv_area_get_width(rect);
int32_t h = lv_area_get_height(rect);
int32_t short_side = LV_MIN(w, h);
if(radius > short_side >> 1) radius = short_side >> 1;
if(radius < 0) radius = 0;
lv_area_copy(¶m->cfg.rect, rect);
param->cfg.radius = radius;
param->cfg.outer = inv ? 1 : 0;
param->dsc.cb = (lv_draw_sw_mask_xcb_t)lv_draw_mask_radius;
param->dsc.type = LV_DRAW_SW_MASK_TYPE_RADIUS;
if(radius == 0) {
param->circle = NULL;
return;
}
lv_mutex_lock(&circle_cache_mutex);
uint32_t i;
/*Try to reuse a circle cache entry*/
for(i = 0; i < LV_DRAW_SW_CIRCLE_CACHE_SIZE; i++) {
if(_circle_cache[i].radius == radius) {
_circle_cache[i].used_cnt++;
CIRCLE_CACHE_AGING(_circle_cache[i].life, radius);
param->circle = &(_circle_cache[i]);
lv_mutex_unlock(&circle_cache_mutex);
return;
}
}
/*If not cached use the free entry with lowest life*/
_lv_draw_sw_mask_radius_circle_dsc_t * entry = NULL;
for(i = 0; i < LV_DRAW_SW_CIRCLE_CACHE_SIZE; i++) {
if(_circle_cache[i].used_cnt == 0) {
if(!entry) entry = &(_circle_cache[i]);
else if(_circle_cache[i].life < entry->life) entry = &(_circle_cache[i]);
}
}
/*There is no unused entry. Allocate one temporarily*/
if(!entry) {
entry = lv_malloc(sizeof(_lv_draw_sw_mask_radius_circle_dsc_t));
LV_ASSERT_MALLOC(entry);
lv_memzero(entry, sizeof(_lv_draw_sw_mask_radius_circle_dsc_t));
entry->life = -1;
}
else {
entry->used_cnt++;
entry->life = 0;
CIRCLE_CACHE_AGING(entry->life, radius);
}
param->circle = entry;
circ_calc_aa4(param->circle, radius);
lv_mutex_unlock(&circle_cache_mutex);
}
/**
* Initialize a fade mask.
* @param param pointer to a `lv_draw_mask_param_t` to initialize
* @param coords coordinates of the area to affect (absolute coordinates)
* @param opa_top opacity on the top
* @param y_top at which coordinate start to change to opacity to `opa_bottom`
* @param opa_bottom opacity at the bottom
* @param y_bottom at which coordinate reach `opa_bottom`.
*/
void lv_draw_sw_mask_fade_init(lv_draw_sw_mask_fade_param_t * param, const lv_area_t * coords, lv_opa_t opa_top,
int32_t y_top,
lv_opa_t opa_bottom, int32_t y_bottom)
{
lv_area_copy(¶m->cfg.coords, coords);
param->cfg.opa_top = opa_top;
param->cfg.opa_bottom = opa_bottom;
param->cfg.y_top = y_top;
param->cfg.y_bottom = y_bottom;
param->dsc.cb = (lv_draw_sw_mask_xcb_t)lv_draw_mask_fade;
param->dsc.type = LV_DRAW_SW_MASK_TYPE_FADE;
}
/**
* Initialize a map mask.
* @param param pointer to a `lv_draw_mask_param_t` to initialize
* @param coords coordinates of the map (absolute coordinates)
* @param map array of bytes with the mask values
*/
void lv_draw_sw_mask_map_init(lv_draw_sw_mask_map_param_t * param, const lv_area_t * coords, const lv_opa_t * map)
{
lv_area_copy(¶m->cfg.coords, coords);
param->cfg.map = map;
param->dsc.cb = (lv_draw_sw_mask_xcb_t)lv_draw_mask_map;
param->dsc.type = LV_DRAW_SW_MASK_TYPE_MAP;
}
/**********************
* STATIC FUNCTIONS
**********************/
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t lv_draw_mask_line(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y, int32_t len,
lv_draw_sw_mask_line_param_t * p)
{
/*Make to points relative to the vertex*/
abs_y -= p->origo.y;
abs_x -= p->origo.x;
/*Handle special cases*/
if(p->steep == 0) {
/*Horizontal*/
if(p->flat) {
/*Non sense: Can't be on the right/left of a horizontal line*/
if(p->cfg.side == LV_DRAW_SW_MASK_LINE_SIDE_LEFT ||
p->cfg.side == LV_DRAW_SW_MASK_LINE_SIDE_RIGHT) return LV_DRAW_SW_MASK_RES_FULL_COVER;
else if(p->cfg.side == LV_DRAW_SW_MASK_LINE_SIDE_TOP && abs_y + 1 < 0) return LV_DRAW_SW_MASK_RES_FULL_COVER;
else if(p->cfg.side == LV_DRAW_SW_MASK_LINE_SIDE_BOTTOM && abs_y > 0) return LV_DRAW_SW_MASK_RES_FULL_COVER;
else {
return LV_DRAW_SW_MASK_RES_TRANSP;
}
}
/*Vertical*/
else {
/*Non sense: Can't be on the top/bottom of a vertical line*/
if(p->cfg.side == LV_DRAW_SW_MASK_LINE_SIDE_TOP ||
p->cfg.side == LV_DRAW_SW_MASK_LINE_SIDE_BOTTOM) return LV_DRAW_SW_MASK_RES_FULL_COVER;
else if(p->cfg.side == LV_DRAW_SW_MASK_LINE_SIDE_RIGHT && abs_x > 0) return LV_DRAW_SW_MASK_RES_FULL_COVER;
else if(p->cfg.side == LV_DRAW_SW_MASK_LINE_SIDE_LEFT) {
if(abs_x + len < 0) return LV_DRAW_SW_MASK_RES_FULL_COVER;
else {
int32_t k = - abs_x;
if(k < 0) return LV_DRAW_SW_MASK_RES_TRANSP;
if(k >= 0 && k < len) lv_memzero(&mask_buf[k], len - k);
return LV_DRAW_SW_MASK_RES_CHANGED;
}
}
else {
if(abs_x + len < 0) return LV_DRAW_SW_MASK_RES_TRANSP;
else {
int32_t k = - abs_x;
if(k < 0) k = 0;
if(k >= len) return LV_DRAW_SW_MASK_RES_TRANSP;
else if(k >= 0 && k < len) lv_memzero(&mask_buf[0], k);
return LV_DRAW_SW_MASK_RES_CHANGED;
}
}
}
}
lv_draw_sw_mask_res_t res;
if(p->flat) {
res = line_mask_flat(mask_buf, abs_x, abs_y, len, p);
}
else {
res = line_mask_steep(mask_buf, abs_x, abs_y, len, p);
}
return res;
}
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t line_mask_flat(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y,
int32_t len,
lv_draw_sw_mask_line_param_t * p)
{
int32_t y_at_x;
y_at_x = (int32_t)((int32_t)p->yx_steep * abs_x) >> 10;
if(p->yx_steep > 0) {
if(y_at_x > abs_y) {
if(p->inv) {
return LV_DRAW_SW_MASK_RES_FULL_COVER;
}
else {
return LV_DRAW_SW_MASK_RES_TRANSP;
}
}
}
else {
if(y_at_x < abs_y) {
if(p->inv) {
return LV_DRAW_SW_MASK_RES_FULL_COVER;
}
else {
return LV_DRAW_SW_MASK_RES_TRANSP;
}
}
}
/*At the end of the mask if the limit line is smaller than the mask's y.
*Then the mask is in the "good" area*/
y_at_x = (int32_t)((int32_t)p->yx_steep * (abs_x + len)) >> 10;
if(p->yx_steep > 0) {
if(y_at_x < abs_y) {
if(p->inv) {
return LV_DRAW_SW_MASK_RES_TRANSP;
}
else {
return LV_DRAW_SW_MASK_RES_FULL_COVER;
}
}
}
else {
if(y_at_x > abs_y) {
if(p->inv) {
return LV_DRAW_SW_MASK_RES_TRANSP;
}
else {
return LV_DRAW_SW_MASK_RES_FULL_COVER;
}
}
}
int32_t xe;
if(p->yx_steep > 0) xe = ((abs_y * 256) * p->xy_steep) >> 10;
else xe = (((abs_y + 1) * 256) * p->xy_steep) >> 10;
int32_t xei = xe >> 8;
int32_t xef = xe & 0xFF;
int32_t px_h;
if(xef == 0) px_h = 255;
else px_h = 255 - (((255 - xef) * p->spx) >> 8);
int32_t k = xei - abs_x;
lv_opa_t m;
if(xef) {
if(k >= 0 && k < len) {
m = 255 - (((255 - xef) * (255 - px_h)) >> 9);
if(p->inv) m = 255 - m;
mask_buf[k] = mask_mix(mask_buf[k], m);
}
k++;
}
while(px_h > p->spx) {
if(k >= 0 && k < len) {
m = px_h - (p->spx >> 1);
if(p->inv) m = 255 - m;
mask_buf[k] = mask_mix(mask_buf[k], m);
}
px_h -= p->spx;
k++;
if(k >= len) break;
}
if(k < len && k >= 0) {
int32_t x_inters = (px_h * p->xy_steep) >> 10;
m = (x_inters * px_h) >> 9;
if(p->yx_steep < 0) m = 255 - m;
if(p->inv) m = 255 - m;
mask_buf[k] = mask_mix(mask_buf[k], m);
}
if(p->inv) {
k = xei - abs_x;
if(k > len) {
return LV_DRAW_SW_MASK_RES_TRANSP;
}
if(k >= 0) {
lv_memzero(&mask_buf[0], k);
}
}
else {
k++;
if(k < 0) {
return LV_DRAW_SW_MASK_RES_TRANSP;
}
if(k <= len) {
lv_memzero(&mask_buf[k], len - k);
}
}
return LV_DRAW_SW_MASK_RES_CHANGED;
}
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t line_mask_steep(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y,
int32_t len,
lv_draw_sw_mask_line_param_t * p)
{
int32_t k;
int32_t x_at_y;
/*At the beginning of the mask if the limit line is greater than the mask's y.
*Then the mask is in the "wrong" area*/
x_at_y = (int32_t)((int32_t)p->xy_steep * abs_y) >> 10;
if(p->xy_steep > 0) x_at_y++;
if(x_at_y < abs_x) {
if(p->inv) {
return LV_DRAW_SW_MASK_RES_FULL_COVER;
}
else {
return LV_DRAW_SW_MASK_RES_TRANSP;
}
}
/*At the end of the mask if the limit line is smaller than the mask's y.
*Then the mask is in the "good" area*/
x_at_y = (int32_t)((int32_t)p->xy_steep * (abs_y)) >> 10;
if(x_at_y > abs_x + len) {
if(p->inv) {
return LV_DRAW_SW_MASK_RES_TRANSP;
}
else {
return LV_DRAW_SW_MASK_RES_FULL_COVER;
}
}
/*X start*/
int32_t xs = ((abs_y * 256) * p->xy_steep) >> 10;
int32_t xsi = xs >> 8;
int32_t xsf = xs & 0xFF;
/*X end*/
int32_t xe = (((abs_y + 1) * 256) * p->xy_steep) >> 10;
int32_t xei = xe >> 8;
int32_t xef = xe & 0xFF;
lv_opa_t m;
k = xsi - abs_x;
if(xsi != xei && (p->xy_steep < 0 && xsf == 0)) {
xsf = 0xFF;
xsi = xei;
k--;
}
if(xsi == xei) {
if(k >= 0 && k < len) {
m = (xsf + xef) >> 1;
if(p->inv) m = 255 - m;
mask_buf[k] = mask_mix(mask_buf[k], m);
}
k++;
if(p->inv) {
k = xsi - abs_x;
if(k >= len) {
return LV_DRAW_SW_MASK_RES_TRANSP;
}
if(k >= 0) lv_memzero(&mask_buf[0], k);
}
else {
if(k > len) k = len;
if(k == 0) return LV_DRAW_SW_MASK_RES_TRANSP;
else if(k > 0) lv_memzero(&mask_buf[k], len - k);
}
}
else {
int32_t y_inters;
if(p->xy_steep < 0) {
y_inters = (xsf * (-p->yx_steep)) >> 10;
if(k >= 0 && k < len) {
m = (y_inters * xsf) >> 9;
if(p->inv) m = 255 - m;
mask_buf[k] = mask_mix(mask_buf[k], m);
}
k--;
int32_t x_inters = ((255 - y_inters) * (-p->xy_steep)) >> 10;
if(k >= 0 && k < len) {
m = 255 - (((255 - y_inters) * x_inters) >> 9);
if(p->inv) m = 255 - m;
mask_buf[k] = mask_mix(mask_buf[k], m);
}
k += 2;
if(p->inv) {
k = xsi - abs_x - 1;
if(k > len) k = len;
else if(k > 0) lv_memzero(&mask_buf[0], k);
}
else {
if(k > len) return LV_DRAW_SW_MASK_RES_FULL_COVER;
if(k >= 0) lv_memzero(&mask_buf[k], len - k);
}
}
else {
y_inters = ((255 - xsf) * p->yx_steep) >> 10;
if(k >= 0 && k < len) {
m = 255 - ((y_inters * (255 - xsf)) >> 9);
if(p->inv) m = 255 - m;
mask_buf[k] = mask_mix(mask_buf[k], m);
}
k++;
int32_t x_inters = ((255 - y_inters) * p->xy_steep) >> 10;
if(k >= 0 && k < len) {
m = ((255 - y_inters) * x_inters) >> 9;
if(p->inv) m = 255 - m;
mask_buf[k] = mask_mix(mask_buf[k], m);
}
k++;
if(p->inv) {
k = xsi - abs_x;
if(k > len) return LV_DRAW_SW_MASK_RES_TRANSP;
if(k >= 0) lv_memzero(&mask_buf[0], k);
}
else {
if(k > len) k = len;
if(k == 0) return LV_DRAW_SW_MASK_RES_TRANSP;
else if(k > 0) lv_memzero(&mask_buf[k], len - k);
}
}
}
return LV_DRAW_SW_MASK_RES_CHANGED;
}
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t lv_draw_mask_angle(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y, int32_t len,
lv_draw_sw_mask_angle_param_t * p)
{
int32_t rel_y = abs_y - p->cfg.vertex_p.y;
int32_t rel_x = abs_x - p->cfg.vertex_p.x;
if(p->cfg.start_angle < 180 && p->cfg.end_angle < 180 &&
p->cfg.start_angle != 0 && p->cfg.end_angle != 0 &&
p->cfg.start_angle > p->cfg.end_angle) {
if(abs_y < p->cfg.vertex_p.y) {
return LV_DRAW_SW_MASK_RES_FULL_COVER;
}
/*Start angle mask can work only from the end of end angle mask*/
int32_t end_angle_first = (rel_y * p->end_line.xy_steep) >> 10;
int32_t start_angle_last = ((rel_y + 1) * p->start_line.xy_steep) >> 10;
/*Do not let the line end cross the vertex else it will affect the opposite part*/
if(p->cfg.start_angle > 270 && p->cfg.start_angle <= 359 && start_angle_last < 0) start_angle_last = 0;
else if(p->cfg.start_angle > 0 && p->cfg.start_angle <= 90 && start_angle_last < 0) start_angle_last = 0;
else if(p->cfg.start_angle > 90 && p->cfg.start_angle < 270 && start_angle_last > 0) start_angle_last = 0;
if(p->cfg.end_angle > 270 && p->cfg.end_angle <= 359 && start_angle_last < 0) start_angle_last = 0;
else if(p->cfg.end_angle > 0 && p->cfg.end_angle <= 90 && start_angle_last < 0) start_angle_last = 0;
else if(p->cfg.end_angle > 90 && p->cfg.end_angle < 270 && start_angle_last > 0) start_angle_last = 0;
int32_t dist = (end_angle_first - start_angle_last) >> 1;
lv_draw_sw_mask_res_t res1 = LV_DRAW_SW_MASK_RES_FULL_COVER;
lv_draw_sw_mask_res_t res2 = LV_DRAW_SW_MASK_RES_FULL_COVER;
int32_t tmp = start_angle_last + dist - rel_x;
if(tmp > len) tmp = len;
if(tmp > 0) {
res1 = lv_draw_mask_line(&mask_buf[0], abs_x, abs_y, tmp, &p->start_line);
if(res1 == LV_DRAW_SW_MASK_RES_TRANSP) {
lv_memzero(&mask_buf[0], tmp);
}
}
if(tmp > len) tmp = len;
if(tmp < 0) tmp = 0;
res2 = lv_draw_mask_line(&mask_buf[tmp], abs_x + tmp, abs_y, len - tmp, &p->end_line);
if(res2 == LV_DRAW_SW_MASK_RES_TRANSP) {
lv_memzero(&mask_buf[tmp], len - tmp);
}
if(res1 == res2) return res1;
else return LV_DRAW_SW_MASK_RES_CHANGED;
}
else if(p->cfg.start_angle > 180 && p->cfg.end_angle > 180 && p->cfg.start_angle > p->cfg.end_angle) {
if(abs_y > p->cfg.vertex_p.y) {
return LV_DRAW_SW_MASK_RES_FULL_COVER;
}
/*Start angle mask can work only from the end of end angle mask*/
int32_t end_angle_first = (rel_y * p->end_line.xy_steep) >> 10;
int32_t start_angle_last = ((rel_y + 1) * p->start_line.xy_steep) >> 10;
/*Do not let the line end cross the vertex else it will affect the opposite part*/
if(p->cfg.start_angle > 270 && p->cfg.start_angle <= 359 && start_angle_last < 0) start_angle_last = 0;
else if(p->cfg.start_angle > 0 && p->cfg.start_angle <= 90 && start_angle_last < 0) start_angle_last = 0;
else if(p->cfg.start_angle > 90 && p->cfg.start_angle < 270 && start_angle_last > 0) start_angle_last = 0;
if(p->cfg.end_angle > 270 && p->cfg.end_angle <= 359 && start_angle_last < 0) start_angle_last = 0;
else if(p->cfg.end_angle > 0 && p->cfg.end_angle <= 90 && start_angle_last < 0) start_angle_last = 0;
else if(p->cfg.end_angle > 90 && p->cfg.end_angle < 270 && start_angle_last > 0) start_angle_last = 0;
int32_t dist = (end_angle_first - start_angle_last) >> 1;
lv_draw_sw_mask_res_t res1 = LV_DRAW_SW_MASK_RES_FULL_COVER;
lv_draw_sw_mask_res_t res2 = LV_DRAW_SW_MASK_RES_FULL_COVER;
int32_t tmp = start_angle_last + dist - rel_x;
if(tmp > len) tmp = len;
if(tmp > 0) {
res1 = lv_draw_mask_line(&mask_buf[0], abs_x, abs_y, tmp, (lv_draw_sw_mask_line_param_t *)&p->end_line);
if(res1 == LV_DRAW_SW_MASK_RES_TRANSP) {
lv_memzero(&mask_buf[0], tmp);
}
}
if(tmp > len) tmp = len;
if(tmp < 0) tmp = 0;
res2 = lv_draw_mask_line(&mask_buf[tmp], abs_x + tmp, abs_y, len - tmp, (lv_draw_sw_mask_line_param_t *)&p->start_line);
if(res2 == LV_DRAW_SW_MASK_RES_TRANSP) {
lv_memzero(&mask_buf[tmp], len - tmp);
}
if(res1 == res2) return res1;
else return LV_DRAW_SW_MASK_RES_CHANGED;
}
else {
lv_draw_sw_mask_res_t res1 = LV_DRAW_SW_MASK_RES_FULL_COVER;
lv_draw_sw_mask_res_t res2 = LV_DRAW_SW_MASK_RES_FULL_COVER;
if(p->cfg.start_angle == 180) {
if(abs_y < p->cfg.vertex_p.y) res1 = LV_DRAW_SW_MASK_RES_FULL_COVER;
else res1 = LV_DRAW_SW_MASK_RES_UNKNOWN;
}
else if(p->cfg.start_angle == 0) {
if(abs_y < p->cfg.vertex_p.y) res1 = LV_DRAW_SW_MASK_RES_UNKNOWN;
else res1 = LV_DRAW_SW_MASK_RES_FULL_COVER;
}
else if((p->cfg.start_angle < 180 && abs_y < p->cfg.vertex_p.y) ||
(p->cfg.start_angle > 180 && abs_y >= p->cfg.vertex_p.y)) {
res1 = LV_DRAW_SW_MASK_RES_UNKNOWN;
}
else {
res1 = lv_draw_mask_line(mask_buf, abs_x, abs_y, len, &p->start_line);
}
if(p->cfg.end_angle == 180) {
if(abs_y < p->cfg.vertex_p.y) res2 = LV_DRAW_SW_MASK_RES_UNKNOWN;
else res2 = LV_DRAW_SW_MASK_RES_FULL_COVER;
}
else if(p->cfg.end_angle == 0) {
if(abs_y < p->cfg.vertex_p.y) res2 = LV_DRAW_SW_MASK_RES_FULL_COVER;
else res2 = LV_DRAW_SW_MASK_RES_UNKNOWN;
}
else if((p->cfg.end_angle < 180 && abs_y < p->cfg.vertex_p.y) ||
(p->cfg.end_angle > 180 && abs_y >= p->cfg.vertex_p.y)) {
res2 = LV_DRAW_SW_MASK_RES_UNKNOWN;
}
else {
res2 = lv_draw_mask_line(mask_buf, abs_x, abs_y, len, &p->end_line);
}
if(res1 == LV_DRAW_SW_MASK_RES_TRANSP || res2 == LV_DRAW_SW_MASK_RES_TRANSP) return LV_DRAW_SW_MASK_RES_TRANSP;
else if(res1 == LV_DRAW_SW_MASK_RES_UNKNOWN && res2 == LV_DRAW_SW_MASK_RES_UNKNOWN) return LV_DRAW_SW_MASK_RES_TRANSP;
else if(res1 == LV_DRAW_SW_MASK_RES_FULL_COVER &&
res2 == LV_DRAW_SW_MASK_RES_FULL_COVER) return LV_DRAW_SW_MASK_RES_FULL_COVER;
else return LV_DRAW_SW_MASK_RES_CHANGED;
}
}
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t lv_draw_mask_radius(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y, int32_t len,
lv_draw_sw_mask_radius_param_t * p)
{
bool outer = p->cfg.outer;
int32_t radius = p->cfg.radius;
lv_area_t rect;
lv_area_copy(&rect, &p->cfg.rect);
if(outer == false) {
if((abs_y < rect.y1 || abs_y > rect.y2)) {
return LV_DRAW_SW_MASK_RES_TRANSP;
}
}
else {
if(abs_y < rect.y1 || abs_y > rect.y2) {
return LV_DRAW_SW_MASK_RES_FULL_COVER;
}
}
if((abs_x >= rect.x1 + radius && abs_x + len <= rect.x2 - radius) ||
(abs_y >= rect.y1 + radius && abs_y <= rect.y2 - radius)) {
if(outer == false) {
/*Remove the edges*/
int32_t last = rect.x1 - abs_x;
if(last > len) return LV_DRAW_SW_MASK_RES_TRANSP;
if(last >= 0) {
lv_memzero(&mask_buf[0], last);
}
int32_t first = rect.x2 - abs_x + 1;
if(first <= 0) return LV_DRAW_SW_MASK_RES_TRANSP;
else if(first < len) {
lv_memzero(&mask_buf[first], len - first);
}
if(last == 0 && first == len) return LV_DRAW_SW_MASK_RES_FULL_COVER;
else return LV_DRAW_SW_MASK_RES_CHANGED;
}
else {
int32_t first = rect.x1 - abs_x;
if(first < 0) first = 0;
if(first <= len) {
int32_t last = rect.x2 - abs_x - first + 1;
if(first + last > len) last = len - first;
if(last >= 0) {
lv_memzero(&mask_buf[first], last);
}
}
}
return LV_DRAW_SW_MASK_RES_CHANGED;
}
int32_t k = rect.x1 - abs_x; /*First relevant coordinate on the of the mask*/
int32_t w = lv_area_get_width(&rect);
int32_t h = lv_area_get_height(&rect);
abs_x -= rect.x1;
abs_y -= rect.y1;
int32_t aa_len;
int32_t x_start;
int32_t cir_y;
if(abs_y < radius) {
cir_y = radius - abs_y - 1;
}
else {
cir_y = abs_y - (h - radius);
}
lv_opa_t * aa_opa = get_next_line(p->circle, cir_y, &aa_len, &x_start);
int32_t cir_x_right = k + w - radius + x_start;
int32_t cir_x_left = k + radius - x_start - 1;
int32_t i;
if(outer == false) {
for(i = 0; i < aa_len; i++) {
lv_opa_t opa = aa_opa[aa_len - i - 1];
if(cir_x_right + i >= 0 && cir_x_right + i < len) {
mask_buf[cir_x_right + i] = mask_mix(opa, mask_buf[cir_x_right + i]);
}
if(cir_x_left - i >= 0 && cir_x_left - i < len) {
mask_buf[cir_x_left - i] = mask_mix(opa, mask_buf[cir_x_left - i]);
}
}
/*Clean the right side*/
cir_x_right = LV_CLAMP(0, cir_x_right + i, len);
lv_memzero(&mask_buf[cir_x_right], len - cir_x_right);
/*Clean the left side*/
cir_x_left = LV_CLAMP(0, cir_x_left - aa_len + 1, len);
lv_memzero(&mask_buf[0], cir_x_left);
}
else {
for(i = 0; i < aa_len; i++) {
lv_opa_t opa = 255 - (aa_opa[aa_len - 1 - i]);
if(cir_x_right + i >= 0 && cir_x_right + i < len) {
mask_buf[cir_x_right + i] = mask_mix(opa, mask_buf[cir_x_right + i]);
}
if(cir_x_left - i >= 0 && cir_x_left - i < len) {
mask_buf[cir_x_left - i] = mask_mix(opa, mask_buf[cir_x_left - i]);
}
}
int32_t clr_start = LV_CLAMP(0, cir_x_left + 1, len);
int32_t clr_len = LV_CLAMP(0, cir_x_right - clr_start, len - clr_start);
lv_memzero(&mask_buf[clr_start], clr_len);
}
return LV_DRAW_SW_MASK_RES_CHANGED;
}
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t lv_draw_mask_fade(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y, int32_t len,
lv_draw_sw_mask_fade_param_t * p)
{
if(abs_y < p->cfg.coords.y1) return LV_DRAW_SW_MASK_RES_FULL_COVER;
if(abs_y > p->cfg.coords.y2) return LV_DRAW_SW_MASK_RES_FULL_COVER;
if(abs_x + len < p->cfg.coords.x1) return LV_DRAW_SW_MASK_RES_FULL_COVER;
if(abs_x > p->cfg.coords.x2) return LV_DRAW_SW_MASK_RES_FULL_COVER;
if(abs_x + len > p->cfg.coords.x2) len -= abs_x + len - p->cfg.coords.x2 - 1;
if(abs_x < p->cfg.coords.x1) {
int32_t x_ofs = 0;
x_ofs = p->cfg.coords.x1 - abs_x;
len -= x_ofs;
mask_buf += x_ofs;
}
int32_t i;
if(abs_y <= p->cfg.y_top) {
for(i = 0; i < len; i++) {
mask_buf[i] = mask_mix(mask_buf[i], p->cfg.opa_top);
}
return LV_DRAW_SW_MASK_RES_CHANGED;
}
else if(abs_y >= p->cfg.y_bottom) {
for(i = 0; i < len; i++) {
mask_buf[i] = mask_mix(mask_buf[i], p->cfg.opa_bottom);
}
return LV_DRAW_SW_MASK_RES_CHANGED;
}
else {
/*Calculate the opa proportionally*/
int16_t opa_diff = p->cfg.opa_bottom - p->cfg.opa_top;
int32_t y_diff = p->cfg.y_bottom - p->cfg.y_top + 1;
lv_opa_t opa_act = LV_OPA_MIX2(abs_y - p->cfg.y_top, opa_diff) / y_diff;
opa_act += p->cfg.opa_top;
for(i = 0; i < len; i++) {
mask_buf[i] = mask_mix(mask_buf[i], opa_act);
}
return LV_DRAW_SW_MASK_RES_CHANGED;
}
}
LV_ATTRIBUTE_FAST_MEM static lv_draw_sw_mask_res_t lv_draw_mask_map(lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y, int32_t len,
lv_draw_sw_mask_map_param_t * p)
{
/*Handle out of the mask cases*/
if(abs_y < p->cfg.coords.y1) return LV_DRAW_SW_MASK_RES_FULL_COVER;
if(abs_y > p->cfg.coords.y2) return LV_DRAW_SW_MASK_RES_FULL_COVER;
if(abs_x + len < p->cfg.coords.x1) return LV_DRAW_SW_MASK_RES_FULL_COVER;
if(abs_x > p->cfg.coords.x2) return LV_DRAW_SW_MASK_RES_FULL_COVER;
/*Got to the current row in the map*/
const lv_opa_t * map_tmp = p->cfg.map;
map_tmp += (abs_y - p->cfg.coords.y1) * lv_area_get_width(&p->cfg.coords);
if(abs_x + len > p->cfg.coords.x2) len -= abs_x + len - p->cfg.coords.x2 - 1;
if(abs_x < p->cfg.coords.x1) {
int32_t x_ofs = 0;
x_ofs = p->cfg.coords.x1 - abs_x;
len -= x_ofs;
mask_buf += x_ofs;
}
else {
map_tmp += (abs_x - p->cfg.coords.x1);
}
int32_t i;
for(i = 0; i < len; i++) {
mask_buf[i] = mask_mix(mask_buf[i], map_tmp[i]);
}
return LV_DRAW_SW_MASK_RES_CHANGED;
}
/**
* Initialize the circle drawing
* @param c pointer to a point. The coordinates will be calculated here
* @param tmp point to a variable. It will store temporary data
* @param radius radius of the circle
*/
static void circ_init(lv_point_t * c, int32_t * tmp, int32_t radius)
{
c->x = radius;
c->y = 0;
*tmp = 1 - radius;
}
/**
* Test the circle drawing is ready or not
* @param c same as in circ_init
* @return true if the circle is not ready yet
*/
static bool circ_cont(lv_point_t * c)
{
return c->y <= c->x;
}
/**
* Get the next point from the circle
* @param c same as in circ_init. The next point stored here.
* @param tmp same as in circ_init.
*/
static void circ_next(lv_point_t * c, int32_t * tmp)
{
if(*tmp <= 0) {
(*tmp) += 2 * c->y + 3; /*Change in decision criterion for y -> y+1*/
}
else {
(*tmp) += 2 * (c->y - c->x) + 5; /*Change for y -> y+1, x -> x-1*/
c->x--;
}
c->y++;
}
static void circ_calc_aa4(_lv_draw_sw_mask_radius_circle_dsc_t * c, int32_t radius)
{
if(radius == 0) return;
c->radius = radius;
/*Allocate buffers*/
if(c->buf) lv_free(c->buf);
c->buf = lv_malloc(radius * 6 + 6); /*Use uint16_t for opa_start_on_y and x_start_on_y*/
LV_ASSERT_MALLOC(c->buf);
c->cir_opa = c->buf;
c->opa_start_on_y = (uint16_t *)(c->buf + 2 * radius + 2);
c->x_start_on_y = (uint16_t *)(c->buf + 4 * radius + 4);
/*Special case, handle manually*/
if(radius == 1) {
c->cir_opa[0] = 180;
c->opa_start_on_y[0] = 0;
c->opa_start_on_y[1] = 1;
c->x_start_on_y[0] = 0;
return;
}
const size_t cir_xy_size = (radius + 1) * 2 * 2 * sizeof(int32_t);
int32_t * cir_x = lv_malloc(cir_xy_size);
lv_memset(cir_x, 0, cir_xy_size);
int32_t * cir_y = &cir_x[(radius + 1) * 2];
uint32_t y_8th_cnt = 0;
lv_point_t cp;
int32_t tmp;
circ_init(&cp, &tmp, radius * 4); /*Upscale by 4*/
int32_t i;
uint32_t x_int[4];
uint32_t x_fract[4];
int32_t cir_size = 0;
x_int[0] = cp.x >> 2;
x_fract[0] = 0;
/*Calculate an 1/8 circle*/
while(circ_cont(&cp)) {
/*Calculate 4 point of the circle */
for(i = 0; i < 4; i++) {
circ_next(&cp, &tmp);
if(circ_cont(&cp) == false) break;
x_int[i] = cp.x >> 2;
x_fract[i] = cp.x & 0x3;
}
if(i != 4) break;
/*All lines on the same x when downscaled*/
if(x_int[0] == x_int[3]) {
cir_x[cir_size] = x_int[0];
cir_y[cir_size] = y_8th_cnt;
c->cir_opa[cir_size] = x_fract[0] + x_fract[1] + x_fract[2] + x_fract[3];
c->cir_opa[cir_size] *= 16;
cir_size++;
}
/*Second line on new x when downscaled*/
else if(x_int[0] != x_int[1]) {
cir_x[cir_size] = x_int[0];
cir_y[cir_size] = y_8th_cnt;
c->cir_opa[cir_size] = x_fract[0];
c->cir_opa[cir_size] *= 16;
cir_size++;
cir_x[cir_size] = x_int[0] - 1;
cir_y[cir_size] = y_8th_cnt;
c->cir_opa[cir_size] = 1 * 4 + x_fract[1] + x_fract[2] + x_fract[3];;
c->cir_opa[cir_size] *= 16;
cir_size++;
}
/*Third line on new x when downscaled*/
else if(x_int[0] != x_int[2]) {
cir_x[cir_size] = x_int[0];
cir_y[cir_size] = y_8th_cnt;
c->cir_opa[cir_size] = x_fract[0] + x_fract[1];
c->cir_opa[cir_size] *= 16;
cir_size++;
cir_x[cir_size] = x_int[0] - 1;
cir_y[cir_size] = y_8th_cnt;
c->cir_opa[cir_size] = 2 * 4 + x_fract[2] + x_fract[3];;
c->cir_opa[cir_size] *= 16;
cir_size++;
}
/*Forth line on new x when downscaled*/
else {
cir_x[cir_size] = x_int[0];
cir_y[cir_size] = y_8th_cnt;
c->cir_opa[cir_size] = x_fract[0] + x_fract[1] + x_fract[2];
c->cir_opa[cir_size] *= 16;
cir_size++;
cir_x[cir_size] = x_int[0] - 1;
cir_y[cir_size] = y_8th_cnt;
c->cir_opa[cir_size] = 3 * 4 + x_fract[3];;
c->cir_opa[cir_size] *= 16;
cir_size++;
}
y_8th_cnt++;
}
/*The point on the 1/8 circle is special, calculate it manually*/
int32_t mid = radius * 723;
int32_t mid_int = mid >> 10;
if(cir_x[cir_size - 1] != mid_int || cir_y[cir_size - 1] != mid_int) {
int32_t tmp_val = mid - (mid_int << 10);
if(tmp_val <= 512) {
tmp_val = tmp_val * tmp_val * 2;
tmp_val = tmp_val >> (10 + 6);
}
else {
tmp_val = 1024 - tmp_val;
tmp_val = tmp_val * tmp_val * 2;
tmp_val = tmp_val >> (10 + 6);
tmp_val = 15 - tmp_val;
}
cir_x[cir_size] = mid_int;
cir_y[cir_size] = mid_int;
c->cir_opa[cir_size] = tmp_val;
c->cir_opa[cir_size] *= 16;
cir_size++;
}
/*Build the second octet by mirroring the first*/
for(i = cir_size - 2; i >= 0; i--, cir_size++) {
cir_x[cir_size] = cir_y[i];
cir_y[cir_size] = cir_x[i];
c->cir_opa[cir_size] = c->cir_opa[i];
}
int32_t y = 0;
i = 0;
c->opa_start_on_y[0] = 0;
while(i < cir_size) {
c->opa_start_on_y[y] = i;
c->x_start_on_y[y] = cir_x[i];
for(; cir_y[i] == y && i < (int32_t)cir_size; i++) {
c->x_start_on_y[y] = LV_MIN(c->x_start_on_y[y], cir_x[i]);
}
y++;
}
lv_free(cir_x);
}
static lv_opa_t * get_next_line(_lv_draw_sw_mask_radius_circle_dsc_t * c, int32_t y, int32_t * len,
int32_t * x_start)
{
*len = c->opa_start_on_y[y + 1] - c->opa_start_on_y[y];
*x_start = c->x_start_on_y[y];
return &c->cir_opa[c->opa_start_on_y[y]];
}
LV_ATTRIBUTE_FAST_MEM static inline lv_opa_t mask_mix(lv_opa_t mask_act, lv_opa_t mask_new)
{
if(mask_new >= LV_OPA_MAX) return mask_act;
if(mask_new <= LV_OPA_MIN) return 0;
return LV_UDIV255(mask_act * mask_new);
}
#endif /*LV_DRAW_SW_COMPLEX*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_triangle.c | /**
* @file lv_draw_sw_triangle.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_draw_sw.h"
#if LV_USE_DRAW_SW
#include "../../misc/lv_math.h"
#include "../../stdlib/lv_mem.h"
#include "../../misc/lv_area.h"
#include "../../misc/lv_color.h"
#include "../../stdlib/lv_string.h"
#include "../lv_draw_triangle.h"
#include "lv_draw_sw_gradient.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static lv_point_t point_to_normal(const lv_point_precise_t * p);
static void point_swap(lv_point_t * p1, lv_point_t * p2);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_sw_triangle(lv_draw_unit_t * draw_unit, const lv_draw_triangle_dsc_t * dsc)
{
#if LV_DRAW_SW_COMPLEX
lv_area_t tri_area;
tri_area.x1 = (int32_t)LV_MIN3(dsc->p[0].x, dsc->p[1].x, dsc->p[2].x);
tri_area.y1 = (int32_t)LV_MIN3(dsc->p[0].y, dsc->p[1].y, dsc->p[2].y);
tri_area.x2 = (int32_t)LV_MAX3(dsc->p[0].x, dsc->p[1].x, dsc->p[2].x);
tri_area.y2 = (int32_t)LV_MAX3(dsc->p[0].y, dsc->p[1].y, dsc->p[2].y);
bool is_common;
lv_area_t draw_area;
is_common = _lv_area_intersect(&draw_area, &tri_area, draw_unit->clip_area);
if(!is_common) return;
lv_point_t p[3];
/*If there is a vertical side use it as p[0] and p[1]*/
if(dsc->p[0].x == dsc->p[1].x) {
p[0] = point_to_normal(&dsc->p[0]);
p[1] = point_to_normal(&dsc->p[1]);
p[2] = point_to_normal(&dsc->p[2]);
}
else if(dsc->p[0].x == dsc->p[2].x) {
p[0] = point_to_normal(&dsc->p[0]);
p[1] = point_to_normal(&dsc->p[2]);
p[2] = point_to_normal(&dsc->p[1]);
}
else if(dsc->p[1].x == dsc->p[2].x) {
p[0] = point_to_normal(&dsc->p[1]);
p[1] = point_to_normal(&dsc->p[2]);
p[2] = point_to_normal(&dsc->p[0]);
}
else {
p[0] = point_to_normal(&dsc->p[0]);
p[1] = point_to_normal(&dsc->p[1]);
p[2] = point_to_normal(&dsc->p[2]);
/*Set the smallest y as p[0]*/
if(p[0].y > p[1].y) point_swap(&p[0], &p[1]);
if(p[0].y > p[2].y) point_swap(&p[0], &p[2]);
/*Set the greatest y as p[1]*/
if(p[1].y < p[2].y) point_swap(&p[1], &p[2]);
}
/*Be sure p[0] is on the top*/
if(p[0].y > p[1].y) point_swap(&p[0], &p[1]);
/*If right == true p[2] is on the right side of the p[0] p[1] line*/
bool right = ((p[1].x - p[0].x) * (p[2].y - p[0].y) - (p[1].y - p[0].y) * (p[2].x - p[0].x)) < 0;
void * masks[4] = {0};
lv_draw_sw_mask_line_param_t mask_left;
lv_draw_sw_mask_line_param_t mask_right;
lv_draw_sw_mask_line_param_t mask_bottom;
lv_draw_sw_mask_line_points_init(&mask_left, p[0].x, p[0].y,
p[1].x, p[1].y,
right ? LV_DRAW_SW_MASK_LINE_SIDE_RIGHT : LV_DRAW_SW_MASK_LINE_SIDE_LEFT);
lv_draw_sw_mask_line_points_init(&mask_right, p[0].x, p[0].y,
p[2].x, p[2].y,
right ? LV_DRAW_SW_MASK_LINE_SIDE_LEFT : LV_DRAW_SW_MASK_LINE_SIDE_RIGHT);
lv_draw_sw_mask_line_points_init(&mask_bottom, p[1].x, p[1].y,
p[2].x, p[2].y,
right ? LV_DRAW_SW_MASK_LINE_SIDE_LEFT : LV_DRAW_SW_MASK_LINE_SIDE_RIGHT);
masks[0] = &mask_left;
masks[1] = &mask_right;
masks[2] = &mask_bottom;
int32_t area_w = lv_area_get_width(&draw_area);
lv_opa_t * mask_buf = lv_malloc(area_w);
lv_area_t blend_area = draw_area;
blend_area.y2 = blend_area.y1;
lv_draw_sw_blend_dsc_t blend_dsc;
blend_dsc.color = dsc->bg_color;
blend_dsc.opa = dsc->bg_opa;
blend_dsc.mask_buf = mask_buf;
blend_dsc.blend_area = &blend_area;
blend_dsc.mask_area = &blend_area;
blend_dsc.blend_mode = LV_BLEND_MODE_NORMAL;
blend_dsc.src_buf = NULL;
lv_grad_dir_t grad_dir = dsc->bg_grad.dir;
lv_grad_t * grad = lv_gradient_get(&dsc->bg_grad, lv_area_get_width(&tri_area), lv_area_get_height(&tri_area));
lv_opa_t * grad_opa_map = NULL;
if(grad && grad_dir == LV_GRAD_DIR_HOR) {
blend_dsc.src_area = &blend_area;
blend_dsc.src_buf = grad->color_map + draw_area.x1 - tri_area.x1;
grad_opa_map = grad->opa_map + draw_area.x1 - tri_area.x1;
blend_dsc.src_color_format = LV_COLOR_FORMAT_RGB888;
}
int32_t y;
for(y = draw_area.y1; y <= draw_area.y2; y++) {
blend_area.y1 = y;
blend_area.y2 = y;
lv_memset(mask_buf, 0xff, area_w);
blend_dsc.mask_res = lv_draw_sw_mask_apply(masks, mask_buf, draw_area.x1, y, area_w);
if(grad_dir == LV_GRAD_DIR_VER) {
blend_dsc.color = grad->color_map[y - tri_area.y1];
blend_dsc.opa = grad->opa_map[y - tri_area.y1];
if(dsc->bg_opa < LV_OPA_MAX) blend_dsc.opa = LV_OPA_MIX2(blend_dsc.opa, dsc->bg_opa);
}
else if(grad_dir == LV_GRAD_DIR_HOR) {
if(grad_opa_map) {
int32_t i;
if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_CHANGED) {
blend_dsc.mask_buf = mask_buf;
for(i = 0; i < area_w; i++) {
if(grad_opa_map[i] < LV_OPA_MAX) mask_buf[i] = LV_OPA_MIX2(mask_buf[i], grad_opa_map[i]);
}
}
else if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_FULL_COVER) {
blend_dsc.mask_buf = grad_opa_map;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
}
else if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_TRANSP) {
continue;
}
}
}
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
lv_free(mask_buf);
lv_draw_sw_mask_free_param(&mask_bottom);
lv_draw_sw_mask_free_param(&mask_left);
lv_draw_sw_mask_free_param(&mask_right);
if(grad) {
lv_gradient_cleanup(grad);
}
#else
LV_UNUSED(draw_unit);
LV_UNUSED(dsc);
LV_LOG_WARN("Can't draw triangles with LV_DRAW_SW_COMPLEX == 0");
#endif /*LV_DRAW_SW_COMPLEX*/
}
/**********************
* STATIC FUNCTIONS
**********************/
static lv_point_t point_to_normal(const lv_point_precise_t * p)
{
lv_point_t p_out;
p_out.x = (int32_t)p->x;
p_out.y = (int32_t)p->y;
return p_out;
}
static void point_swap(lv_point_t * p1, lv_point_t * p2)
{
lv_point_t tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
#endif /*LV_USE_DRAW_SW*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_gradient.c | /**
* @file lv_draw_sw_gradient.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_draw_sw_gradient.h"
#if LV_USE_DRAW_SW
#include "../../misc/lv_types.h"
#include "../../osal/lv_os.h"
/*********************
* DEFINES
*********************/
#define GRAD_CM(r,g,b) lv_color_make(r,g,b)
#define GRAD_CONV(t, x) t = x
#undef ALIGN
#if defined(LV_ARCH_64)
#define ALIGN(X) (((X) + 7) & ~7)
#else
#define ALIGN(X) (((X) + 3) & ~3)
#endif
/**********************
* STATIC PROTOTYPES
**********************/
typedef lv_result_t (*op_cache_t)(lv_grad_t * c, void * ctx);
static lv_grad_t * allocate_item(const lv_grad_dsc_t * g, int32_t w, int32_t h);
/**********************
* STATIC VARIABLE
**********************/
/**********************
* STATIC FUNCTIONS
**********************/
static lv_grad_t * allocate_item(const lv_grad_dsc_t * g, int32_t w, int32_t h)
{
int32_t size = g->dir == LV_GRAD_DIR_HOR ? w : h;
size_t req_size = ALIGN(sizeof(lv_grad_t)) + ALIGN(size * sizeof(lv_color_t)) + ALIGN(size * sizeof(lv_opa_t));
lv_grad_t * item = lv_malloc(req_size);
LV_ASSERT_MALLOC(item);
if(item == NULL) return NULL;
uint8_t * p = (uint8_t *)item;
item->color_map = (lv_color_t *)(p + ALIGN(sizeof(*item)));
item->opa_map = (lv_opa_t *)(p + ALIGN(sizeof(*item)) + ALIGN(size * sizeof(lv_color_t)));
item->size = size;
return item;
}
/**********************
* FUNCTIONS
**********************/
lv_grad_t * lv_gradient_get(const lv_grad_dsc_t * g, int32_t w, int32_t h)
{
/* No gradient, no cache */
if(g->dir == LV_GRAD_DIR_NONE) return NULL;
/* Step 1: Search cache for the given key */
lv_grad_t * item = allocate_item(g, w, h);
if(item == NULL) {
LV_LOG_WARN("Failed to allocate item for the gradient");
return item;
}
/* Step 3: Fill it with the gradient, as expected */
uint32_t i;
for(i = 0; i < item->size; i++) {
lv_gradient_color_calculate(g, item->size, i, &item->color_map[i], &item->opa_map[i]);
}
return item;
}
LV_ATTRIBUTE_FAST_MEM void lv_gradient_color_calculate(const lv_grad_dsc_t * dsc, int32_t range,
int32_t frac, lv_grad_color_t * color_out, lv_opa_t * opa_out)
{
lv_grad_color_t tmp;
/*Clip out-of-bounds first*/
int32_t min = (dsc->stops[0].frac * range) >> 8;
if(frac <= min) {
GRAD_CONV(tmp, dsc->stops[0].color);
*color_out = tmp;
*opa_out = dsc->stops[0].opa;
return;
}
int32_t max = (dsc->stops[dsc->stops_count - 1].frac * range) >> 8;
if(frac >= max) {
GRAD_CONV(tmp, dsc->stops[dsc->stops_count - 1].color);
*color_out = tmp;
*opa_out = dsc->stops[dsc->stops_count - 1].opa;
return;
}
/*Find the 2 closest stop now*/
int32_t d = 0;
int32_t found_i = 0;
for(uint8_t i = 1; i < dsc->stops_count; i++) {
int32_t cur = (dsc->stops[i].frac * range) >> 8;
if(frac <= cur) {
found_i = i;
break;
}
}
LV_ASSERT(found_i != 0);
lv_color_t one, two;
one = dsc->stops[found_i - 1].color;
two = dsc->stops[found_i].color;
min = (dsc->stops[found_i - 1].frac * range) >> 8;
max = (dsc->stops[found_i].frac * range) >> 8;
d = max - min;
/*Then interpolate*/
frac -= min;
lv_opa_t mix = (frac * 255) / d;
lv_opa_t imix = 255 - mix;
*color_out = GRAD_CM(LV_UDIV255(two.red * mix + one.red * imix),
LV_UDIV255(two.green * mix + one.green * imix),
LV_UDIV255(two.blue * mix + one.blue * imix));
*opa_out = LV_UDIV255(dsc->stops[found_i].opa * mix + dsc->stops[found_i - 1].opa * imix);
}
void lv_gradient_cleanup(lv_grad_t * grad)
{
lv_free(grad);
}
#endif /*LV_USE_DRAW_SW*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_mask_rect.c | /**
* @file lv_draw_sw_mask_rect.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../lv_draw.h"
#if LV_USE_DRAW_SW
#if LV_DRAW_SW_COMPLEX
#include "../../misc/lv_math.h"
#include "../../misc/lv_log.h"
#include "../../stdlib/lv_mem.h"
#include "../../stdlib/lv_string.h"
#include "lv_draw_sw.h"
#include "lv_draw_sw_mask.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_sw_mask_rect(lv_draw_unit_t * draw_unit, const lv_draw_mask_rect_dsc_t * dsc, const lv_area_t * coords)
{
LV_UNUSED(coords);
lv_area_t draw_area;
if(!_lv_area_intersect(&draw_area, &dsc->area, draw_unit->clip_area)) {
return;
}
lv_draw_sw_mask_radius_param_t param;
lv_draw_sw_mask_radius_init(¶m, &dsc->area, dsc->radius, false);
void * masks[2] = {0};
masks[0] = ¶m;
uint32_t area_w = lv_area_get_width(&draw_area);
lv_opa_t * mask_buf = lv_malloc(area_w);
int32_t y;
for(y = draw_area.y1; y <= draw_area.y2; y++) {
lv_memset(mask_buf, 0xff, area_w);
lv_draw_sw_mask_res_t res = lv_draw_sw_mask_apply(masks, mask_buf, draw_area.x1, y, area_w);
if(res == LV_DRAW_SW_MASK_RES_FULL_COVER) continue;
lv_layer_t * target_layer = draw_unit->target_layer;
lv_color32_t * c32_buf = lv_draw_layer_go_to_xy(target_layer, draw_area.x1 - target_layer->buf_area.x1,
y - target_layer->buf_area.y1);
if(res == LV_DRAW_SW_MASK_RES_TRANSP) {
uint32_t i;
for(i = 0; i < area_w; i++) {
c32_buf[i].alpha = 0x00;
}
}
else {
uint32_t i;
for(i = 0; i < area_w; i++) {
if(mask_buf[i] != LV_OPA_COVER) {
c32_buf[i].alpha = LV_OPA_MIX2(c32_buf[i].alpha, mask_buf[i]);
}
}
}
}
lv_free(mask_buf);
lv_draw_sw_mask_free_param(¶m);
}
/**********************
* STATIC FUNCTIONS
**********************/
#endif /*LV_DRAW_SW_COMPLEX*/
#endif /*LV_USE_DRAW_SW*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_transform.c | /**
* @file lv_draw_sw_transform.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_draw_sw.h"
#if LV_USE_DRAW_SW
#include "../../misc/lv_assert.h"
#include "../../misc/lv_area.h"
#include "../../core/lv_refr.h"
#include "../../misc/lv_color.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
int32_t x_in;
int32_t y_in;
int32_t x_out;
int32_t y_out;
int32_t sinma;
int32_t cosma;
int32_t scale_x;
int32_t scale_y;
int32_t angle;
int32_t pivot_x_256;
int32_t pivot_y_256;
lv_point_t pivot;
} point_transform_dsc_t;
/**********************
* STATIC PROTOTYPES
**********************/
/**
* Transform a point with 1/256 precision (the output coordinates are upscaled by 256)
* @param t pointer to n initialized `point_transform_dsc_t` structure
* @param xin X coordinate to rotate
* @param yin Y coordinate to rotate
* @param xout upscaled, transformed X
* @param yout upscaled, transformed Y
*/
static void transform_point_upscaled(point_transform_dsc_t * t, int32_t xin, int32_t yin, int32_t * xout,
int32_t * yout);
static void transform_rgb888(const uint8_t * src, int32_t src_w, int32_t src_h, int32_t src_stride,
int32_t xs_ups, int32_t ys_ups, int32_t xs_step, int32_t ys_step,
int32_t x_end, uint8_t * dest_buf, bool aa, uint32_t px_size);
static void transform_argb8888(const uint8_t * src, int32_t src_w, int32_t src_h, int32_t src_stride,
int32_t xs_ups, int32_t ys_ups, int32_t xs_step, int32_t ys_step,
int32_t x_end, uint8_t * dest_buf, bool aa);
static void transform_rgb565a8(const uint8_t * src, int32_t src_w, int32_t src_h, int32_t src_stride,
int32_t xs_ups, int32_t ys_ups, int32_t xs_step, int32_t ys_step,
int32_t x_end, uint16_t * cbuf, uint8_t * abuf, bool src_has_a8, bool aa);
static void transform_a8(const uint8_t * src, int32_t src_w, int32_t src_h, int32_t src_stride,
int32_t xs_ups, int32_t ys_ups, int32_t xs_step, int32_t ys_step,
int32_t x_end, uint8_t * abuf, bool aa);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_sw_transform(lv_draw_unit_t * draw_unit, const lv_area_t * dest_area, const void * src_buf,
int32_t src_w, int32_t src_h, int32_t src_stride,
const lv_draw_image_dsc_t * draw_dsc, const lv_draw_image_sup_t * sup, lv_color_format_t src_cf, void * dest_buf)
{
LV_UNUSED(draw_unit);
LV_UNUSED(sup);
point_transform_dsc_t tr_dsc;
tr_dsc.angle = -draw_dsc->rotation;
tr_dsc.scale_x = (256 * 256) / draw_dsc->scale_x;
tr_dsc.scale_y = (256 * 256) / draw_dsc->scale_y;
tr_dsc.pivot = draw_dsc->pivot;
int32_t angle_low = tr_dsc.angle / 10;
int32_t angle_high = angle_low + 1;
int32_t angle_rem = tr_dsc.angle - (angle_low * 10);
int32_t s1 = lv_trigo_sin(angle_low);
int32_t s2 = lv_trigo_sin(angle_high);
int32_t c1 = lv_trigo_sin(angle_low + 90);
int32_t c2 = lv_trigo_sin(angle_high + 90);
tr_dsc.sinma = (s1 * (10 - angle_rem) + s2 * angle_rem) / 10;
tr_dsc.cosma = (c1 * (10 - angle_rem) + c2 * angle_rem) / 10;
tr_dsc.sinma = tr_dsc.sinma >> (LV_TRIGO_SHIFT - 10);
tr_dsc.cosma = tr_dsc.cosma >> (LV_TRIGO_SHIFT - 10);
tr_dsc.pivot_x_256 = tr_dsc.pivot.x * 256;
tr_dsc.pivot_y_256 = tr_dsc.pivot.y * 256;
int32_t dest_w = lv_area_get_width(dest_area);
int32_t dest_h = lv_area_get_height(dest_area);
int32_t dest_stride_a8 = dest_w;
int32_t dest_stride;
int32_t src_stride_px;
if(src_cf == LV_COLOR_FORMAT_RGB888) {
dest_stride = lv_draw_buf_width_to_stride(dest_w, LV_COLOR_FORMAT_ARGB8888);
src_stride_px = src_stride / lv_color_format_get_size(LV_COLOR_FORMAT_RGB888);
}
else if(src_cf == LV_COLOR_FORMAT_RGB565A8) {
dest_stride = lv_draw_buf_width_to_stride(dest_w, LV_COLOR_FORMAT_RGB565);
src_stride_px = src_stride / lv_color_format_get_size(LV_COLOR_FORMAT_RGB565);
}
else {
dest_stride = lv_draw_buf_width_to_stride(dest_w, src_cf);
src_stride_px = src_stride / lv_color_format_get_size(src_cf);
}
uint8_t * alpha_buf;
if(src_cf == LV_COLOR_FORMAT_RGB565 || src_cf == LV_COLOR_FORMAT_RGB565A8) {
alpha_buf = dest_buf;
alpha_buf += dest_stride * dest_h;
}
else {
alpha_buf = NULL;
}
bool aa = draw_dsc->antialias;
int32_t y;
for(y = 0; y < dest_h; y++) {
int32_t xs1_ups, ys1_ups, xs2_ups, ys2_ups;
transform_point_upscaled(&tr_dsc, dest_area->x1, dest_area->y1 + y, &xs1_ups, &ys1_ups);
transform_point_upscaled(&tr_dsc, dest_area->x2, dest_area->y1 + y, &xs2_ups, &ys2_ups);
int32_t xs_diff = xs2_ups - xs1_ups;
int32_t ys_diff = ys2_ups - ys1_ups;
int32_t xs_step_256 = 0;
int32_t ys_step_256 = 0;
if(dest_w > 1) {
xs_step_256 = (256 * xs_diff) / (dest_w - 1);
ys_step_256 = (256 * ys_diff) / (dest_w - 1);
}
int32_t xs_ups = xs1_ups + 0x80;
int32_t ys_ups = ys1_ups + 0x80;
switch(src_cf) {
case LV_COLOR_FORMAT_XRGB8888:
transform_rgb888(src_buf, src_w, src_h, src_stride_px, xs_ups, ys_ups, xs_step_256, ys_step_256, dest_w, dest_buf, aa,
4);
break;
case LV_COLOR_FORMAT_RGB888:
transform_rgb888(src_buf, src_w, src_h, src_stride_px, xs_ups, ys_ups, xs_step_256, ys_step_256, dest_w, dest_buf, aa,
3);
break;
case LV_COLOR_FORMAT_A8:
transform_a8(src_buf, src_w, src_h, src_stride_px, xs_ups, ys_ups, xs_step_256, ys_step_256, dest_w, dest_buf, aa);
break;
case LV_COLOR_FORMAT_ARGB8888:
transform_argb8888(src_buf, src_w, src_h, src_stride_px, xs_ups, ys_ups, xs_step_256, ys_step_256, dest_w, dest_buf,
aa);
break;
case LV_COLOR_FORMAT_RGB565:
transform_rgb565a8(src_buf, src_w, src_h, src_stride_px, xs_ups, ys_ups, xs_step_256, ys_step_256, dest_w, dest_buf,
alpha_buf, false, aa);
break;
case LV_COLOR_FORMAT_RGB565A8:
transform_rgb565a8(src_buf, src_w, src_h, src_stride_px, xs_ups, ys_ups, xs_step_256, ys_step_256, dest_w,
(uint16_t *)dest_buf,
alpha_buf, true, aa);
break;
default:
break;
}
dest_buf = (uint8_t *)dest_buf + dest_stride;
if(alpha_buf) alpha_buf += dest_stride_a8;
}
}
/**********************
* STATIC FUNCTIONS
**********************/
static void transform_rgb888(const uint8_t * src, int32_t src_w, int32_t src_h, int32_t src_stride,
int32_t xs_ups, int32_t ys_ups, int32_t xs_step, int32_t ys_step,
int32_t x_end, uint8_t * dest_buf, bool aa, uint32_t px_size)
{
int32_t xs_ups_start = xs_ups;
int32_t ys_ups_start = ys_ups;
lv_color32_t * dest_c32 = (lv_color32_t *) dest_buf;
int32_t x;
for(x = 0; x < x_end; x++) {
xs_ups = xs_ups_start + ((xs_step * x) >> 8);
ys_ups = ys_ups_start + ((ys_step * x) >> 8);
int32_t xs_int = xs_ups >> 8;
int32_t ys_int = ys_ups >> 8;
/*Fully out of the image*/
if(xs_int < 0 || xs_int >= src_w || ys_int < 0 || ys_int >= src_h) {
dest_c32[x].alpha = 0x00;
continue;
}
/*Get the direction the hor and ver neighbor
*`fract` will be in range of 0x00..0xFF and `next` (+/-1) indicates the direction*/
int32_t xs_fract = xs_ups & 0xFF;
int32_t ys_fract = ys_ups & 0xFF;
int32_t x_next;
int32_t y_next;
if(xs_fract < 0x80) {
x_next = -1;
xs_fract = 0x7F - xs_fract;
}
else {
x_next = 1;
xs_fract = xs_fract - 0x80;
}
if(ys_fract < 0x80) {
y_next = -1;
ys_fract = 0x7F - ys_fract;
}
else {
y_next = 1;
ys_fract = ys_fract - 0x80;
}
const uint8_t * src_u8 = &src[ys_int * src_stride * px_size + xs_int * px_size];
dest_c32[x].red = src_u8[2];
dest_c32[x].green = src_u8[1];
dest_c32[x].blue = src_u8[0];
dest_c32[x].alpha = 0xff;
if(aa &&
xs_int + x_next >= 0 &&
xs_int + x_next <= src_w - 1 &&
ys_int + y_next >= 0 &&
ys_int + y_next <= src_h - 1) {
const uint8_t * px_hor_u8 = src_u8 + (int32_t)(x_next * px_size);
lv_color32_t px_hor;
px_hor.red = px_hor_u8[2];
px_hor.green = px_hor_u8[1];
px_hor.blue = px_hor_u8[0];
px_hor.alpha = 0xff;
const uint8_t * px_ver_u8 = src_u8 + (int32_t)(y_next * src_stride * px_size);
lv_color32_t px_ver;
px_ver.red = px_ver_u8[2];
px_ver.green = px_ver_u8[1];
px_ver.blue = px_ver_u8[0];
px_ver.alpha = 0xff;
if(!lv_color32_eq(dest_c32[x], px_ver)) {
px_ver.alpha = ys_fract;
dest_c32[x] = lv_color_mix32(px_ver, dest_c32[x]);
}
if(!lv_color32_eq(dest_c32[x], px_hor)) {
px_hor.alpha = xs_fract;
dest_c32[x] = lv_color_mix32(px_hor, dest_c32[x]);
}
}
/*Partially out of the image*/
else {
lv_opa_t a = 0xff;
if((xs_int == 0 && x_next < 0) || (xs_int == src_w - 1 && x_next > 0)) {
dest_c32[x].alpha = (a * (0xFF - xs_fract)) >> 8;
}
else if((ys_int == 0 && y_next < 0) || (ys_int == src_h - 1 && y_next > 0)) {
dest_c32[x].alpha = (a * (0xFF - ys_fract)) >> 8;
}
else {
dest_c32[x].alpha = 0x00;
}
}
}
}
#include "../../stdlib/lv_string.h"
static void transform_argb8888(const uint8_t * src, int32_t src_w, int32_t src_h, int32_t src_stride,
int32_t xs_ups, int32_t ys_ups, int32_t xs_step, int32_t ys_step,
int32_t x_end, uint8_t * dest_buf, bool aa)
{
// lv_memzero(dest_buf, x_end * 4);
int32_t xs_ups_start = xs_ups;
int32_t ys_ups_start = ys_ups;
lv_color32_t * dest_c32 = (lv_color32_t *) dest_buf;
int32_t x;
for(x = 0; x < x_end; x++) {
xs_ups = xs_ups_start + ((xs_step * x) >> 8);
ys_ups = ys_ups_start + ((ys_step * x) >> 8);
int32_t xs_int = xs_ups >> 8;
int32_t ys_int = ys_ups >> 8;
/*Fully out of the image*/
if(xs_int < 0 || xs_int >= src_w || ys_int < 0 || ys_int >= src_h) {
((uint32_t *)dest_buf)[x] = 0x00000000;
continue;
}
/*Get the direction the hor and ver neighbor
*`fract` will be in range of 0x00..0xFF and `next` (+/-1) indicates the direction*/
int32_t xs_fract = xs_ups & 0xFF;
int32_t ys_fract = ys_ups & 0xFF;
int32_t x_next;
int32_t y_next;
if(xs_fract < 0x80) {
x_next = -1;
xs_fract = 0x7F - xs_fract;
}
else {
x_next = 1;
xs_fract = xs_fract - 0x80;
}
if(ys_fract < 0x80) {
y_next = -1;
ys_fract = 0x7F - ys_fract;
}
else {
y_next = 1;
ys_fract = ys_fract - 0x80;
}
const lv_color32_t * src_c32 = (const lv_color32_t *)src;
src_c32 += (ys_int * src_stride) + xs_int;
dest_c32[x] = src_c32[0];
if(aa &&
xs_int + x_next >= 0 &&
xs_int + x_next <= src_w - 1 &&
ys_int + y_next >= 0 &&
ys_int + y_next <= src_h - 1) {
lv_color32_t px_hor = src_c32[x_next];
lv_color32_t px_ver = src_c32[y_next * src_stride];
if(px_ver.alpha == 0) {
dest_c32[x].alpha = (dest_c32[x].alpha * (0xFF - ys_fract)) >> 8;
}
else if(!lv_color32_eq(dest_c32[x], px_ver)) {
dest_c32[x].alpha = ((px_ver.alpha * ys_fract) + (dest_c32[x].alpha * (0xFF - ys_fract))) >> 8;
px_ver.alpha = ys_fract;
dest_c32[x] = lv_color_mix32(px_ver, dest_c32[x]);
}
if(px_hor.alpha == 0) {
dest_c32[x].alpha = (dest_c32[x].alpha * (0xFF - xs_fract)) >> 8;
}
else if(!lv_color32_eq(dest_c32[x], px_hor)) {
dest_c32[x].alpha = ((px_hor.alpha * xs_fract) + (dest_c32[x].alpha * (0xFF - xs_fract))) >> 8;
px_hor.alpha = xs_fract;
dest_c32[x] = lv_color_mix32(px_hor, dest_c32[x]);
}
}
/*Partially out of the image*/
else {
if((xs_int == 0 && x_next < 0) || (xs_int == src_w - 1 && x_next > 0)) {
dest_c32[x].alpha = (dest_c32[x].alpha * (0x7F - xs_fract)) >> 7;
}
else if((ys_int == 0 && y_next < 0) || (ys_int == src_h - 1 && y_next > 0)) {
dest_c32[x].alpha = (dest_c32[x].alpha * (0x7F - ys_fract)) >> 7;
}
else {
dest_c32[x].alpha = 0x00;
}
}
}
}
static void transform_rgb565a8(const uint8_t * src, int32_t src_w, int32_t src_h, int32_t src_stride,
int32_t xs_ups, int32_t ys_ups, int32_t xs_step, int32_t ys_step,
int32_t x_end, uint16_t * cbuf, uint8_t * abuf, bool src_has_a8, bool aa)
{
int32_t xs_ups_start = xs_ups;
int32_t ys_ups_start = ys_ups;
const uint16_t * src_rgb = (const uint16_t *)src;
const lv_opa_t * src_alpha = src + src_stride * src_h * 2;
int32_t x;
for(x = 0; x < x_end; x++) {
xs_ups = xs_ups_start + ((xs_step * x) >> 8);
ys_ups = ys_ups_start + ((ys_step * x) >> 8);
int32_t xs_int = xs_ups >> 8;
int32_t ys_int = ys_ups >> 8;
/*Fully out of the image*/
if(xs_int < 0 || xs_int >= src_w || ys_int < 0 || ys_int >= src_h) {
abuf[x] = 0x00;
continue;
}
/*Get the direction the hor and ver neighbor
*`fract` will be in range of 0x00..0xFF and `next` (+/-1) indicates the direction*/
int32_t xs_fract = xs_ups & 0xFF;
int32_t ys_fract = ys_ups & 0xFF;
int32_t x_next;
int32_t y_next;
if(xs_fract < 0x80) {
x_next = -1;
xs_fract = (0x7F - xs_fract) * 2;
}
else {
x_next = 1;
xs_fract = (xs_fract - 0x80) * 2;
}
if(ys_fract < 0x80) {
y_next = -1;
ys_fract = (0x7F - ys_fract) * 2;
}
else {
y_next = 1;
ys_fract = (ys_fract - 0x80) * 2;
}
const uint16_t * src_tmp_u16 = (const uint16_t *)src_rgb;
src_tmp_u16 += (ys_int * src_stride) + xs_int;
cbuf[x] = src_tmp_u16[0];
if(aa &&
xs_int + x_next >= 0 &&
xs_int + x_next <= src_w - 1 &&
ys_int + y_next >= 0 &&
ys_int + y_next <= src_h - 1) {
uint16_t px_hor = src_tmp_u16[x_next];
uint16_t px_ver = src_tmp_u16[y_next * src_stride];
if(src_has_a8) {
const lv_opa_t * src_alpha_tmp = src_alpha;
src_alpha_tmp += (ys_int * src_stride) + xs_int;
abuf[x] = src_alpha_tmp[0];
lv_opa_t a_hor = src_alpha_tmp[x_next];
lv_opa_t a_ver = src_alpha_tmp[y_next * src_stride];
if(a_ver != abuf[x]) a_ver = ((a_ver * ys_fract) + (abuf[x] * (0x100 - ys_fract))) >> 8;
if(a_hor != abuf[x]) a_hor = ((a_hor * xs_fract) + (abuf[x] * (0x100 - xs_fract))) >> 8;
abuf[x] = (a_ver + a_hor) >> 1;
if(abuf[x] == 0x00) continue;
}
else {
abuf[x] = 0xff;
}
if(cbuf[x] != px_ver || cbuf[x] != px_hor) {
uint16_t v = lv_color_16_16_mix(px_ver, cbuf[x], ys_fract);
uint16_t h = lv_color_16_16_mix(px_hor, cbuf[x], xs_fract);
cbuf[x] = lv_color_16_16_mix(h, v, LV_OPA_50);
}
}
/*Partially out of the image*/
else {
lv_opa_t a;
if(src_has_a8) {
const lv_opa_t * src_alpha_tmp = src_alpha;
src_alpha_tmp += (ys_int * src_stride) + xs_int;
a = src_alpha_tmp[0];
}
else {
a = 0xff;
}
if((xs_int == 0 && x_next < 0) || (xs_int == src_w - 1 && x_next > 0)) {
abuf[x] = (a * (0xFF - xs_fract)) >> 8;
}
else if((ys_int == 0 && y_next < 0) || (ys_int == src_h - 1 && y_next > 0)) {
abuf[x] = (a * (0xFF - ys_fract)) >> 8;
}
else {
abuf[x] = 0x00;
}
}
}
}
static void transform_a8(const uint8_t * src, int32_t src_w, int32_t src_h, int32_t src_stride,
int32_t xs_ups, int32_t ys_ups, int32_t xs_step, int32_t ys_step,
int32_t x_end, uint8_t * abuf, bool aa)
{
int32_t xs_ups_start = xs_ups;
int32_t ys_ups_start = ys_ups;
int32_t x;
for(x = 0; x < x_end; x++) {
xs_ups = xs_ups_start + ((xs_step * x) >> 8);
ys_ups = ys_ups_start + ((ys_step * x) >> 8);
int32_t xs_int = xs_ups >> 8;
int32_t ys_int = ys_ups >> 8;
/*Fully out of the image*/
if(xs_int < 0 || xs_int >= src_w || ys_int < 0 || ys_int >= src_h) {
abuf[x] = 0x00;
continue;
}
/*Get the direction the hor and ver neighbor
*`fract` will be in range of 0x00..0xFF and `next` (+/-1) indicates the direction*/
int32_t xs_fract = xs_ups & 0xFF;
int32_t ys_fract = ys_ups & 0xFF;
int32_t x_next;
int32_t y_next;
if(xs_fract < 0x80) {
x_next = -1;
xs_fract = (0x7F - xs_fract) * 2;
}
else {
x_next = 1;
xs_fract = (xs_fract - 0x80) * 2;
}
if(ys_fract < 0x80) {
y_next = -1;
ys_fract = (0x7F - ys_fract) * 2;
}
else {
y_next = 1;
ys_fract = (ys_fract - 0x80) * 2;
}
const uint8_t * src_tmp = src;
src_tmp += ys_int * src_stride + xs_int;
abuf[x] = src_tmp[0];
if(aa &&
xs_int + x_next >= 0 &&
xs_int + x_next <= src_w - 1 &&
ys_int + y_next >= 0 &&
ys_int + y_next <= src_h - 1) {
lv_opa_t a_ver = src_tmp[x_next];
lv_opa_t a_hor = src_tmp[y_next * src_stride];
if(a_ver != abuf[x]) a_ver = ((a_ver * ys_fract) + (abuf[x] * (0x100 - ys_fract))) >> 8;
if(a_hor != abuf[x]) a_hor = ((a_hor * xs_fract) + (abuf[x] * (0x100 - xs_fract))) >> 8;
abuf[x] = (a_ver + a_hor) >> 1;
}
else {
/*Partially out of the image*/
if((xs_int == 0 && x_next < 0) || (xs_int == src_w - 1 && x_next > 0)) {
abuf[x] = (src_tmp[0] * (0xFF - xs_fract)) >> 8;
}
else if((ys_int == 0 && y_next < 0) || (ys_int == src_h - 1 && y_next > 0)) {
abuf[x] = (src_tmp[0] * (0xFF - ys_fract)) >> 8;
}
else {
abuf[x] = 0x00;
}
}
}
}
static void transform_point_upscaled(point_transform_dsc_t * t, int32_t xin, int32_t yin, int32_t * xout,
int32_t * yout)
{
if(t->angle == 0 && t->scale_x == LV_SCALE_NONE && t->scale_y == LV_SCALE_NONE) {
*xout = xin * 256;
*yout = yin * 256;
return;
}
xin -= t->pivot.x;
yin -= t->pivot.y;
if(t->angle == 0) {
*xout = ((int32_t)(xin * t->scale_x)) + (t->pivot_x_256);
*yout = ((int32_t)(yin * t->scale_y)) + (t->pivot_y_256);
}
else if(t->scale_x == LV_SCALE_NONE && t->scale_y == LV_SCALE_NONE) {
*xout = ((t->cosma * xin - t->sinma * yin) >> 2) + (t->pivot_x_256);
*yout = ((t->sinma * xin + t->cosma * yin) >> 2) + (t->pivot_y_256);
}
else {
*xout = (((t->cosma * xin - t->sinma * yin) * t->scale_x) >> 10) + (t->pivot_x_256);
*yout = (((t->sinma * xin + t->cosma * yin) * t->scale_y) >> 10) + (t->pivot_y_256);
}
}
#endif /*LV_USE_DRAW_SW*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_arc.c | /**
* @file lv_draw_sw_arc.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_draw_sw.h"
#if LV_USE_DRAW_SW
#if LV_DRAW_SW_COMPLEX
#include "../../misc/lv_math.h"
#include "../../misc/lv_log.h"
#include "../../stdlib/lv_mem.h"
#include "../../stdlib/lv_string.h"
#include "../lv_draw.h"
static void add_circle(const lv_opa_t * circle_mask, const lv_area_t * blend_area, const lv_area_t * circle_area,
lv_opa_t * mask_buf, int32_t width);
static void get_rounded_area(int16_t angle, int32_t radius, uint8_t thickness, lv_area_t * res_area);
/*********************
* DEFINES
*********************/
#define SPLIT_RADIUS_LIMIT 10 /*With radius greater than this the arc will drawn in quarters. A quarter is drawn only if there is arc in it*/
#define SPLIT_ANGLE_GAP_LIMIT 60 /*With small gaps in the arc don't bother with splitting because there is nothing to skip.*/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_sw_arc(lv_draw_unit_t * draw_unit, const lv_draw_arc_dsc_t * dsc, const lv_area_t * coords)
{
#if LV_DRAW_SW_COMPLEX
if(dsc->opa <= LV_OPA_MIN) return;
if(dsc->width == 0) return;
if(dsc->start_angle == dsc->end_angle) return;
int32_t width = dsc->width;
if(width > dsc->radius) width = dsc->radius;
lv_area_t area_out = *coords;
lv_area_t clipped_area;
if(!_lv_area_intersect(&clipped_area, &area_out, draw_unit->clip_area)) return;
/*Draw a full ring*/
if(dsc->img_src == NULL &&
(dsc->start_angle + 360 == dsc->end_angle || dsc->start_angle == dsc->end_angle + 360)) {
lv_draw_border_dsc_t cir_dsc;
lv_draw_border_dsc_init(&cir_dsc);
cir_dsc.opa = dsc->opa;
cir_dsc.color = dsc->color;
cir_dsc.width = width;
cir_dsc.radius = LV_RADIUS_CIRCLE;
cir_dsc.side = LV_BORDER_SIDE_FULL;
lv_draw_sw_border(draw_unit, &cir_dsc, &area_out);
return;
}
lv_area_t area_in;
lv_area_copy(&area_in, &area_out);
area_in.x1 += dsc->width;
area_in.y1 += dsc->width;
area_in.x2 -= dsc->width;
area_in.y2 -= dsc->width;
int32_t start_angle = (int32_t)dsc->start_angle;
int32_t end_angle = (int32_t)dsc->end_angle;
while(start_angle >= 360) start_angle -= 360;
while(end_angle >= 360) end_angle -= 360;
void * mask_list[4] = {0};
/*Create an angle mask*/
lv_draw_sw_mask_angle_param_t mask_angle_param;
lv_draw_sw_mask_angle_init(&mask_angle_param, dsc->center.x, dsc->center.y, start_angle, end_angle);
mask_list[0] = &mask_angle_param;
/*Create an outer mask*/
lv_draw_sw_mask_radius_param_t mask_out_param;
lv_draw_sw_mask_radius_init(&mask_out_param, &area_out, LV_RADIUS_CIRCLE, false);
mask_list[1] = &mask_out_param;
/*Create inner the mask*/
lv_draw_sw_mask_radius_param_t mask_in_param;
bool mask_in_param_valid = false;
if(lv_area_get_width(&area_in) > 0 && lv_area_get_height(&area_in) > 0) {
lv_draw_sw_mask_radius_init(&mask_in_param, &area_in, LV_RADIUS_CIRCLE, true);
mask_list[2] = &mask_in_param;
mask_in_param_valid = true;
}
int32_t blend_h = lv_area_get_height(&clipped_area);
int32_t blend_w = lv_area_get_width(&clipped_area);
int32_t h;
lv_opa_t * mask_buf = lv_malloc(blend_w);
lv_area_t blend_area = clipped_area;
lv_area_t img_area;
lv_draw_sw_blend_dsc_t blend_dsc = {0};
blend_dsc.mask_buf = mask_buf;
blend_dsc.opa = dsc->opa;
blend_dsc.blend_area = &blend_area;
blend_dsc.mask_area = &blend_area;
if(dsc->img_src == NULL) {
blend_dsc.color = dsc->color;
}
else {
lv_image_decoder_dsc_t decoder_dsc;
lv_image_decoder_open(&decoder_dsc, dsc->img_src, dsc->color, 0);
img_area.x1 = 0;
img_area.y1 = 0;
img_area.x2 = decoder_dsc.header.w - 1;
img_area.y2 = decoder_dsc.header.h - 1;
int32_t ofs = decoder_dsc.header.w / 2;
lv_area_move(&img_area, dsc->center.x - ofs, dsc->center.y - ofs);
blend_dsc.src_area = &img_area;
blend_dsc.src_buf = decoder_dsc.img_data;
blend_dsc.src_color_format = decoder_dsc.header.cf;
blend_dsc.src_stride = decoder_dsc.header.stride;
}
lv_opa_t * circle_mask = NULL;
lv_area_t round_area_1;
lv_area_t round_area_2;
if(dsc->rounded) {
circle_mask = lv_malloc(width * width);
lv_memset(circle_mask, 0xff, width * width);
lv_area_t circle_area = {0, 0, width - 1, width - 1};
lv_draw_sw_mask_radius_param_t circle_mask_param;
lv_draw_sw_mask_radius_init(&circle_mask_param, &circle_area, width / 2, false);
void * circle_mask_list[2] = {&circle_mask_param, NULL};
lv_opa_t * circle_mask_tmp = circle_mask;
for(h = 0; h < width; h++) {
lv_draw_sw_mask_res_t res = lv_draw_sw_mask_apply(circle_mask_list, circle_mask_tmp, 0, h, width);
if(res == LV_DRAW_SW_MASK_RES_TRANSP) {
lv_memzero(circle_mask_tmp, width);
}
circle_mask_tmp += width;
}
get_rounded_area(start_angle, dsc->radius, width, &round_area_1);
lv_area_move(&round_area_1, dsc->center.x, dsc->center.y);
get_rounded_area(end_angle, dsc->radius, width, &round_area_2);
lv_area_move(&round_area_2, dsc->center.x, dsc->center.y);
}
blend_area.y2 = blend_area.y1;
for(h = 0; h < blend_h; h++) {
lv_memset(mask_buf, 0xff, blend_w);
blend_dsc.mask_res = lv_draw_sw_mask_apply(mask_list, mask_buf, blend_area.x1, blend_area.y1, blend_w);
if(dsc->rounded) {
if(blend_area.y1 >= round_area_1.y1 && blend_area.y1 <= round_area_1.y2) {
if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_TRANSP) {
lv_memset(mask_buf, 0x00, blend_w);
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
}
add_circle(circle_mask, &blend_area, &round_area_1, mask_buf, width);
}
if(blend_area.y1 >= round_area_2.y1 && blend_area.y1 <= round_area_2.y2) {
if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_TRANSP) {
lv_memset(mask_buf, 0x00, blend_w);
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
}
add_circle(circle_mask, &blend_area, &round_area_2, mask_buf, width);
}
}
lv_draw_sw_blend(draw_unit, &blend_dsc);
blend_area.y1 ++;
blend_area.y2 ++;
}
lv_draw_sw_mask_free_param(&mask_angle_param);
lv_draw_sw_mask_free_param(&mask_out_param);
if(mask_in_param_valid) {
lv_draw_sw_mask_free_param(&mask_in_param);
}
lv_free(mask_buf);
if(circle_mask) lv_free(circle_mask);
#else
LV_LOG_WARN("Can't draw arc with LV_DRAW_SW_COMPLEX == 0");
LV_UNUSED(center);
LV_UNUSED(radius);
LV_UNUSED(start_angle);
LV_UNUSED(end_angle);
LV_UNUSED(layer);
LV_UNUSED(dsc);
#endif /*LV_DRAW_SW_COMPLEX*/
}
/**********************
* STATIC FUNCTIONS
**********************/
static void add_circle(const lv_opa_t * circle_mask, const lv_area_t * blend_area, const lv_area_t * circle_area,
lv_opa_t * mask_buf, int32_t width)
{
lv_area_t circle_common_area;
if(_lv_area_intersect(&circle_common_area, circle_area, blend_area)) {
const lv_opa_t * circle_mask_tmp = circle_mask + width * (circle_common_area.y1 - circle_area->y1);
circle_mask_tmp += circle_common_area.x1 - circle_area->x1;
lv_opa_t * mask_buf_tmp = mask_buf + circle_common_area.x1 - blend_area->x1;
uint32_t x;
uint32_t w = lv_area_get_width(&circle_common_area);
for(x = 0; x < w; x++) {
uint32_t res = mask_buf_tmp[x] + circle_mask_tmp[x];
mask_buf_tmp[x] = res > 255 ? 255 : res;
}
}
}
static void get_rounded_area(int16_t angle, int32_t radius, uint8_t thickness, lv_area_t * res_area)
{
int32_t thick_half = thickness / 2;
uint8_t thick_corr = (thickness & 0x01) ? 0 : 1;
int32_t cir_x;
int32_t cir_y;
cir_x = ((radius - thick_half) * lv_trigo_cos(angle)) >> (LV_TRIGO_SHIFT - 8);
cir_y = ((radius - thick_half) * lv_trigo_sin(angle)) >> (LV_TRIGO_SHIFT - 8);
/*The center of the pixel need to be calculated so apply 1/2 px offset*/
if(cir_x > 0) {
cir_x = (cir_x - 128) >> 8;
res_area->x1 = cir_x - thick_half + thick_corr;
res_area->x2 = cir_x + thick_half;
}
else {
cir_x = (cir_x + 128) >> 8;
res_area->x1 = cir_x - thick_half;
res_area->x2 = cir_x + thick_half - thick_corr;
}
if(cir_y > 0) {
cir_y = (cir_y - 128) >> 8;
res_area->y1 = cir_y - thick_half + thick_corr;
res_area->y2 = cir_y + thick_half;
}
else {
cir_y = (cir_y + 128) >> 8;
res_area->y1 = cir_y - thick_half;
res_area->y2 = cir_y + thick_half - thick_corr;
}
}
#endif /*LV_DRAW_SW_COMPLEX*/
#endif /*LV_USE_DRAW_SW*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_border.c | /**
* @file lv_draw_sw_border.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_draw_sw.h"
#if LV_USE_DRAW_SW
#include "blend/lv_draw_sw_blend.h"
#include "../../misc/lv_math.h"
#include "../../misc/lv_text_ap.h"
#include "../../core/lv_refr.h"
#include "../../misc/lv_assert.h"
#include "../../stdlib/lv_string.h"
#include "../lv_draw_mask.h"
/*********************
* DEFINES
*********************/
#define SPLIT_LIMIT 50
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void draw_border_complex(lv_draw_unit_t * draw_unit, const lv_area_t * outer_area, const lv_area_t * inner_area,
int32_t rout, int32_t rin, lv_color_t color, lv_opa_t opa);
static void draw_border_simple(lv_draw_unit_t * draw_unit, const lv_area_t * outer_area, const lv_area_t * inner_area,
lv_color_t color, lv_opa_t opa);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_sw_border(lv_draw_unit_t * draw_unit, const lv_draw_border_dsc_t * dsc, const lv_area_t * coords)
{
if(dsc->opa <= LV_OPA_MIN) return;
if(dsc->width == 0) return;
if(dsc->side == LV_BORDER_SIDE_NONE) return;
int32_t coords_w = lv_area_get_width(coords);
int32_t coords_h = lv_area_get_height(coords);
int32_t rout = dsc->radius;
int32_t short_side = LV_MIN(coords_w, coords_h);
if(rout > short_side >> 1) rout = short_side >> 1;
/*Get the inner area*/
lv_area_t area_inner;
lv_area_copy(&area_inner, coords);
area_inner.x1 += ((dsc->side & LV_BORDER_SIDE_LEFT) ? dsc->width : - (dsc->width + rout));
area_inner.x2 -= ((dsc->side & LV_BORDER_SIDE_RIGHT) ? dsc->width : - (dsc->width + rout));
area_inner.y1 += ((dsc->side & LV_BORDER_SIDE_TOP) ? dsc->width : - (dsc->width + rout));
area_inner.y2 -= ((dsc->side & LV_BORDER_SIDE_BOTTOM) ? dsc->width : - (dsc->width + rout));
int32_t rin = rout - dsc->width;
if(rin < 0) rin = 0;
if(rout == 0 && rin == 0) {
draw_border_simple(draw_unit, coords, &area_inner, dsc->color, dsc->opa);
}
else {
draw_border_complex(draw_unit, coords, &area_inner, rout, rin, dsc->color, dsc->opa);
}
}
/**********************
* STATIC FUNCTIONS
**********************/
void draw_border_complex(lv_draw_unit_t * draw_unit, const lv_area_t * outer_area, const lv_area_t * inner_area,
int32_t rout, int32_t rin, lv_color_t color, lv_opa_t opa)
{
#if LV_DRAW_SW_COMPLEX
/*Get clipped draw area which is the real draw area.
*It is always the same or inside `coords`*/
lv_area_t draw_area;
if(!_lv_area_intersect(&draw_area, outer_area, draw_unit->clip_area)) return;
int32_t draw_area_w = lv_area_get_width(&draw_area);
lv_draw_sw_blend_dsc_t blend_dsc;
lv_memzero(&blend_dsc, sizeof(blend_dsc));
lv_opa_t * mask_buf = lv_malloc(draw_area_w);
blend_dsc.mask_buf = mask_buf;
void * mask_list[3] = {0};
/*Create mask for the inner mask*/
lv_draw_sw_mask_radius_param_t mask_rin_param;
lv_draw_sw_mask_radius_init(&mask_rin_param, inner_area, rin, true);
mask_list[0] = &mask_rin_param;
/*Create mask for the outer area*/
lv_draw_sw_mask_radius_param_t mask_rout_param;
if(rout > 0) {
lv_draw_sw_mask_radius_init(&mask_rout_param, outer_area, rout, false);
mask_list[1] = &mask_rout_param;
}
int32_t h;
lv_area_t blend_area;
blend_dsc.blend_area = &blend_area;
blend_dsc.mask_area = &blend_area;
blend_dsc.color = color;
blend_dsc.opa = opa;
/*Calculate the x and y coordinates where the straight parts area is*/
lv_area_t core_area;
core_area.x1 = LV_MAX(outer_area->x1 + rout, inner_area->x1);
core_area.x2 = LV_MIN(outer_area->x2 - rout, inner_area->x2);
core_area.y1 = LV_MAX(outer_area->y1 + rout, inner_area->y1);
core_area.y2 = LV_MIN(outer_area->y2 - rout, inner_area->y2);
int32_t core_w = lv_area_get_width(&core_area);
bool top_side = outer_area->y1 <= inner_area->y1;
bool bottom_side = outer_area->y2 >= inner_area->y2;
/*No masks*/
bool left_side = outer_area->x1 <= inner_area->x1;
bool right_side = outer_area->x2 >= inner_area->x2;
bool split_hor = true;
if(left_side && right_side && top_side && bottom_side &&
core_w < SPLIT_LIMIT) {
split_hor = false;
}
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_FULL_COVER;
/*Draw the straight lines first if they are long enough*/
if(top_side && split_hor) {
blend_area.x1 = core_area.x1;
blend_area.x2 = core_area.x2;
blend_area.y1 = outer_area->y1;
blend_area.y2 = inner_area->y1 - 1;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
if(bottom_side && split_hor) {
blend_area.x1 = core_area.x1;
blend_area.x2 = core_area.x2;
blend_area.y1 = inner_area->y2 + 1;
blend_area.y2 = outer_area->y2;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
/*If the border is very thick and the vertical sides overlap horizontally draw a single rectangle*/
if(inner_area->x1 >= inner_area->x2 && left_side && right_side) {
blend_area.x1 = outer_area->x1;
blend_area.x2 = outer_area->x2;
blend_area.y1 = core_area.y1;
blend_area.y2 = core_area.y2;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
else {
if(left_side) {
blend_area.x1 = outer_area->x1;
blend_area.x2 = inner_area->x1 - 1;
blend_area.y1 = core_area.y1;
blend_area.y2 = core_area.y2;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
if(right_side) {
blend_area.x1 = inner_area->x2 + 1;
blend_area.x2 = outer_area->x2;
blend_area.y1 = core_area.y1;
blend_area.y2 = core_area.y2;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
}
/*Draw the corners*/
int32_t blend_w;
/*Left and right corner together if they are close to each other*/
if(!split_hor) {
/*Calculate the top corner and mirror it to the bottom*/
blend_area.x1 = draw_area.x1;
blend_area.x2 = draw_area.x2;
int32_t max_h = LV_MAX(rout, inner_area->y1 - outer_area->y1);
for(h = 0; h < max_h; h++) {
int32_t top_y = outer_area->y1 + h;
int32_t bottom_y = outer_area->y2 - h;
if(top_y < draw_area.y1 && bottom_y > draw_area.y2) continue; /*This line is clipped now*/
lv_memset(mask_buf, 0xff, draw_area_w);
blend_dsc.mask_res = lv_draw_sw_mask_apply(mask_list, mask_buf, blend_area.x1, top_y, draw_area_w);
if(top_y >= draw_area.y1) {
blend_area.y1 = top_y;
blend_area.y2 = top_y;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
if(bottom_y <= draw_area.y2) {
blend_area.y1 = bottom_y;
blend_area.y2 = bottom_y;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
}
}
else {
/*Left corners*/
blend_area.x1 = draw_area.x1;
blend_area.x2 = LV_MIN(draw_area.x2, core_area.x1 - 1);
blend_w = lv_area_get_width(&blend_area);
if(blend_w > 0) {
if(left_side || top_side) {
for(h = draw_area.y1; h < core_area.y1; h++) {
blend_area.y1 = h;
blend_area.y2 = h;
lv_memset(mask_buf, 0xff, blend_w);
blend_dsc.mask_res = lv_draw_sw_mask_apply(mask_list, mask_buf, blend_area.x1, h, blend_w);
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
}
if(left_side || bottom_side) {
for(h = core_area.y2 + 1; h <= draw_area.y2; h++) {
blend_area.y1 = h;
blend_area.y2 = h;
lv_memset(mask_buf, 0xff, blend_w);
blend_dsc.mask_res = lv_draw_sw_mask_apply(mask_list, mask_buf, blend_area.x1, h, blend_w);
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
}
}
/*Right corners*/
blend_area.x1 = LV_MAX(draw_area.x1, blend_area.x2 + 1); /*To not overlap with the left side*/
blend_area.x1 = LV_MAX(draw_area.x1, core_area.x2 + 1);
blend_area.x2 = draw_area.x2;
blend_w = lv_area_get_width(&blend_area);
if(blend_w > 0) {
if(right_side || top_side) {
for(h = draw_area.y1; h < core_area.y1; h++) {
blend_area.y1 = h;
blend_area.y2 = h;
lv_memset(mask_buf, 0xff, blend_w);
blend_dsc.mask_res = lv_draw_sw_mask_apply(mask_list, mask_buf, blend_area.x1, h, blend_w);
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
}
if(right_side || bottom_side) {
for(h = core_area.y2 + 1; h <= draw_area.y2; h++) {
blend_area.y1 = h;
blend_area.y2 = h;
lv_memset(mask_buf, 0xff, blend_w);
blend_dsc.mask_res = lv_draw_sw_mask_apply(mask_list, mask_buf, blend_area.x1, h, blend_w);
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
}
}
}
lv_draw_sw_mask_free_param(&mask_rin_param);
if(rout > 0) lv_draw_sw_mask_free_param(&mask_rout_param);
lv_free(mask_buf);
#endif /*LV_DRAW_SW_COMPLEX*/
}
static void draw_border_simple(lv_draw_unit_t * draw_unit, const lv_area_t * outer_area, const lv_area_t * inner_area,
lv_color_t color, lv_opa_t opa)
{
lv_area_t a;
lv_draw_sw_blend_dsc_t blend_dsc;
lv_memzero(&blend_dsc, sizeof(lv_draw_sw_blend_dsc_t));
blend_dsc.blend_area = &a;
blend_dsc.color = color;
blend_dsc.opa = opa;
bool top_side = outer_area->y1 <= inner_area->y1;
bool bottom_side = outer_area->y2 >= inner_area->y2;
bool left_side = outer_area->x1 <= inner_area->x1;
bool right_side = outer_area->x2 >= inner_area->x2;
/*Top*/
a.x1 = outer_area->x1;
a.x2 = outer_area->x2;
a.y1 = outer_area->y1;
a.y2 = inner_area->y1 - 1;
if(top_side) {
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
/*Bottom*/
a.y1 = inner_area->y2 + 1;
a.y2 = outer_area->y2;
if(bottom_side) {
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
/*Left*/
a.x1 = outer_area->x1;
a.x2 = inner_area->x1 - 1;
a.y1 = (top_side) ? inner_area->y1 : outer_area->y1;
a.y2 = (bottom_side) ? inner_area->y2 : outer_area->y2;
if(left_side) {
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
/*Right*/
a.x1 = inner_area->x2 + 1;
a.x2 = outer_area->x2;
if(right_side) {
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
}
#endif /*LV_USE_DRAW_SW*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw.h | /**
* @file lv_draw_sw.h
*
*/
#ifndef LV_DRAW_SW_H
#define LV_DRAW_SW_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_draw.h"
#if LV_USE_DRAW_SW
#include "../../misc/lv_area.h"
#include "../../misc/lv_color.h"
#include "../../display/lv_display.h"
#include "../../osal/lv_os.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_draw_unit_t base_unit;
struct _lv_draw_task_t * task_act;
#if LV_USE_OS
lv_thread_sync_t sync;
lv_thread_t thread;
#endif
uint32_t idx;
} lv_draw_sw_unit_t;
#if LV_DRAW_SW_SHADOW_CACHE_SIZE
typedef struct {
uint8_t cache[LV_DRAW_SW_SHADOW_CACHE_SIZE * LV_DRAW_SW_SHADOW_CACHE_SIZE];
int32_t cache_size;
int32_t cache_r;
} lv_draw_sw_shadow_cache_t;
#endif
/**********************
* GLOBAL PROTOTYPES
**********************/
void lv_draw_sw_init(void);
LV_ATTRIBUTE_FAST_MEM void lv_draw_sw_image(lv_draw_unit_t * draw_unit, const lv_draw_image_dsc_t * draw_dsc,
const lv_area_t * coords);
void lv_draw_sw_fill(lv_draw_unit_t * draw_unit, const lv_draw_fill_dsc_t * dsc, const lv_area_t * coords);
void lv_draw_sw_border(lv_draw_unit_t * draw_unit, const lv_draw_border_dsc_t * dsc, const lv_area_t * coords);
void lv_draw_sw_box_shadow(lv_draw_unit_t * draw_unit, const lv_draw_box_shadow_dsc_t * dsc, const lv_area_t * coords);
void lv_draw_sw_bg_image(lv_draw_unit_t * draw_unit, const lv_draw_bg_image_dsc_t * dsc, const lv_area_t * coords);
void lv_draw_sw_label(lv_draw_unit_t * draw_unit, const lv_draw_label_dsc_t * dsc, const lv_area_t * coords);
void lv_draw_sw_arc(lv_draw_unit_t * draw_unit, const lv_draw_arc_dsc_t * dsc, const lv_area_t * coords);
LV_ATTRIBUTE_FAST_MEM void lv_draw_sw_line(lv_draw_unit_t * draw_unit, const lv_draw_line_dsc_t * dsc);
void lv_draw_sw_layer(lv_draw_unit_t * draw_unit, const lv_draw_image_dsc_t * draw_dsc, const lv_area_t * coords);
void lv_draw_sw_triangle(lv_draw_unit_t * draw_unit, const lv_draw_triangle_dsc_t * dsc);
void lv_draw_sw_mask_rect(lv_draw_unit_t * draw_unit, const lv_draw_mask_rect_dsc_t * dsc, const lv_area_t * coords);
void lv_draw_sw_transform(lv_draw_unit_t * draw_unit, const lv_area_t * dest_area, const void * src_buf,
int32_t src_w, int32_t src_h, int32_t src_stride,
const lv_draw_image_dsc_t * draw_dsc, const lv_draw_image_sup_t * sup, lv_color_format_t cf, void * dest_buf);
/***********************
* GLOBAL VARIABLES
***********************/
/**********************
* MACROS
**********************/
#include "blend/lv_draw_sw_blend.h"
#endif /*LV_USE_DRAW_SW*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_SW_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_mask.h | /**
* @file lv_draw_sw_mask.h
*
*/
#ifndef LV_DRAW_SW_MASK_H
#define LV_DRAW_SW_MASK_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include <stdbool.h>
#include "../../misc/lv_area.h"
#include "../../misc/lv_color.h"
#include "../../misc/lv_math.h"
/*********************
* DEFINES
*********************/
#define LV_MASK_ID_INV (-1)
#if LV_DRAW_SW_COMPLEX
# define _LV_MASK_MAX_NUM 16
#else
# define _LV_MASK_MAX_NUM 1
#endif
/**********************
* TYPEDEFS
**********************/
enum {
LV_DRAW_SW_MASK_RES_TRANSP,
LV_DRAW_SW_MASK_RES_FULL_COVER,
LV_DRAW_SW_MASK_RES_CHANGED,
LV_DRAW_SW_MASK_RES_UNKNOWN
};
typedef uint8_t lv_draw_sw_mask_res_t;
#if LV_DRAW_SW_COMPLEX
enum {
LV_DRAW_SW_MASK_TYPE_LINE,
LV_DRAW_SW_MASK_TYPE_ANGLE,
LV_DRAW_SW_MASK_TYPE_RADIUS,
LV_DRAW_SW_MASK_TYPE_FADE,
LV_DRAW_SW_MASK_TYPE_MAP,
};
typedef uint8_t lv_draw_sw_mask_type_t;
enum {
LV_DRAW_SW_MASK_LINE_SIDE_LEFT = 0,
LV_DRAW_SW_MASK_LINE_SIDE_RIGHT,
LV_DRAW_SW_MASK_LINE_SIDE_TOP,
LV_DRAW_SW_MASK_LINE_SIDE_BOTTOM,
};
/**
* A common callback type for every mask type.
* Used internally by the library.
*/
typedef lv_draw_sw_mask_res_t (*lv_draw_sw_mask_xcb_t)(lv_opa_t * mask_buf, int32_t abs_x, int32_t abs_y,
int32_t len,
void * p);
typedef uint8_t lv_draw_sw_mask_line_side_t;
typedef struct {
lv_draw_sw_mask_xcb_t cb;
lv_draw_sw_mask_type_t type;
} _lv_draw_sw_mask_common_dsc_t;
typedef struct {
/*The first element must be the common descriptor*/
_lv_draw_sw_mask_common_dsc_t dsc;
struct {
/*First point*/
lv_point_t p1;
/*Second point*/
lv_point_t p2;
/*Which side to keep?*/
lv_draw_sw_mask_line_side_t side : 2;
} cfg;
/*A point of the line*/
lv_point_t origo;
/*X / (1024*Y) steepness (X is 0..1023 range). What is the change of X in 1024 Y?*/
int32_t xy_steep;
/*Y / (1024*X) steepness (Y is 0..1023 range). What is the change of Y in 1024 X?*/
int32_t yx_steep;
/*Helper which stores yx_steep for flat lines and xy_steep for steep (non flat) lines*/
int32_t steep;
/*Steepness in 1 px in 0..255 range. Used only by flat lines.*/
int32_t spx;
/*1: It's a flat line? (Near to horizontal)*/
uint8_t flat : 1;
/*Invert the mask. The default is: Keep the left part.
*It is used to select left/right/top/bottom*/
uint8_t inv: 1;
} lv_draw_sw_mask_line_param_t;
typedef struct {
/*The first element must be the common descriptor*/
_lv_draw_sw_mask_common_dsc_t dsc;
struct {
lv_point_t vertex_p;
int32_t start_angle;
int32_t end_angle;
} cfg;
lv_draw_sw_mask_line_param_t start_line;
lv_draw_sw_mask_line_param_t end_line;
uint16_t delta_deg;
} lv_draw_sw_mask_angle_param_t;
typedef struct {
uint8_t * buf;
lv_opa_t * cir_opa; /*Opacity of values on the circumference of an 1/4 circle*/
uint16_t * x_start_on_y; /*The x coordinate of the circle for each y value*/
uint16_t * opa_start_on_y; /*The index of `cir_opa` for each y value*/
int32_t life; /*How many times the entry way used*/
uint32_t used_cnt; /*Like a semaphore to count the referencing masks*/
int32_t radius; /*The radius of the entry*/
} _lv_draw_sw_mask_radius_circle_dsc_t;
typedef _lv_draw_sw_mask_radius_circle_dsc_t _lv_draw_sw_mask_radius_circle_dsc_arr_t[LV_DRAW_SW_CIRCLE_CACHE_SIZE];
typedef struct {
/*The first element must be the common descriptor*/
_lv_draw_sw_mask_common_dsc_t dsc;
struct {
lv_area_t rect;
int32_t radius;
/*Invert the mask. 0: Keep the pixels inside.*/
uint8_t outer: 1;
} cfg;
_lv_draw_sw_mask_radius_circle_dsc_t * circle;
} lv_draw_sw_mask_radius_param_t;
typedef struct {
/*The first element must be the common descriptor*/
_lv_draw_sw_mask_common_dsc_t dsc;
struct {
lv_area_t coords;
int32_t y_top;
int32_t y_bottom;
lv_opa_t opa_top;
lv_opa_t opa_bottom;
} cfg;
} lv_draw_sw_mask_fade_param_t;
typedef struct _lv_draw_sw_mask_map_param_t {
/*The first element must be the common descriptor*/
_lv_draw_sw_mask_common_dsc_t dsc;
struct {
lv_area_t coords;
const lv_opa_t * map;
} cfg;
} lv_draw_sw_mask_map_param_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
void lv_draw_sw_mask_init(void);
//! @cond Doxygen_Suppress
/**
* Apply the added buffers on a line. Used internally by the library's drawing routines.
* @param masks the masks list to apply, must be ended with NULL pointer in array.
* @param mask_buf store the result mask here. Has to be `len` byte long. Should be initialized with `0xFF`.
* @param abs_x absolute X coordinate where the line to calculate start
* @param abs_y absolute Y coordinate where the line to calculate start
* @param len length of the line to calculate (in pixel count)
* @return One of these values:
* - `LV_DRAW_MASK_RES_FULL_TRANSP`: the whole line is transparent. `mask_buf` is not set to zero
* - `LV_DRAW_MASK_RES_FULL_COVER`: the whole line is fully visible. `mask_buf` is unchanged
* - `LV_DRAW_MASK_RES_CHANGED`: `mask_buf` has changed, it shows the desired opacity of each pixel in the given line
*/
LV_ATTRIBUTE_FAST_MEM lv_draw_sw_mask_res_t lv_draw_sw_mask_apply(void * masks[], lv_opa_t * mask_buf, int32_t abs_x,
int32_t abs_y,
int32_t len);
//! @endcond
/**
* Free the data from the parameter.
* It's called inside `lv_draw_sw_mask_remove_id` and `lv_draw_sw_mask_remove_custom`
* Needs to be called only in special cases when the mask is not added by `lv_draw_mask_add`
* and not removed by `lv_draw_mask_remove_id` or `lv_draw_mask_remove_custom`
* @param p pointer to a mask parameter
*/
void lv_draw_sw_mask_free_param(void * p);
/**
* Called by LVGL the rendering of a screen is ready to clean up
* the temporal (cache) data of the masks
*/
void _lv_draw_sw_mask_cleanup(void);
/**
*Initialize a line mask from two points.
* @param param pointer to a `lv_draw_mask_param_t` to initialize
* @param p1x X coordinate of the first point of the line
* @param p1y Y coordinate of the first point of the line
* @param p2x X coordinate of the second point of the line
* @param p2y y coordinate of the second point of the line
* @param side and element of `lv_draw_mask_line_side_t` to describe which side to keep.
* With `LV_DRAW_MASK_LINE_SIDE_LEFT/RIGHT` and horizontal line all pixels are kept
* With `LV_DRAW_MASK_LINE_SIDE_TOP/BOTTOM` and vertical line all pixels are kept
*/
void lv_draw_sw_mask_line_points_init(lv_draw_sw_mask_line_param_t * param, int32_t p1x, int32_t p1y,
int32_t p2x,
int32_t p2y, lv_draw_sw_mask_line_side_t side);
/**
*Initialize a line mask from a point and an angle.
* @param param pointer to a `lv_draw_mask_param_t` to initialize
* @param px X coordinate of a point of the line
* @param py X coordinate of a point of the line
* @param angle right 0 deg, bottom: 90
* @param side and element of `lv_draw_mask_line_side_t` to describe which side to keep.
* With `LV_DRAW_MASK_LINE_SIDE_LEFT/RIGHT` and horizontal line all pixels are kept
* With `LV_DRAW_MASK_LINE_SIDE_TOP/BOTTOM` and vertical line all pixels are kept
*/
void lv_draw_sw_mask_line_angle_init(lv_draw_sw_mask_line_param_t * param, int32_t p1x, int32_t py, int16_t angle,
lv_draw_sw_mask_line_side_t side);
/**
* Initialize an angle mask.
* @param param pointer to a `lv_draw_mask_param_t` to initialize
* @param vertex_x X coordinate of the angle vertex (absolute coordinates)
* @param vertex_y Y coordinate of the angle vertex (absolute coordinates)
* @param start_angle start angle in degrees. 0 deg on the right, 90 deg, on the bottom
* @param end_angle end angle
*/
void lv_draw_sw_mask_angle_init(lv_draw_sw_mask_angle_param_t * param, int32_t vertex_x, int32_t vertex_y,
int32_t start_angle, int32_t end_angle);
/**
* Initialize a fade mask.
* @param param pointer to an `lv_draw_mask_radius_param_t` to initialize
* @param rect coordinates of the rectangle to affect (absolute coordinates)
* @param radius radius of the rectangle
* @param inv true: keep the pixels inside the rectangle; keep the pixels outside of the rectangle
*/
void lv_draw_sw_mask_radius_init(lv_draw_sw_mask_radius_param_t * param, const lv_area_t * rect, int32_t radius,
bool inv);
/**
* Initialize a fade mask.
* @param param pointer to a `lv_draw_mask_param_t` to initialize
* @param coords coordinates of the area to affect (absolute coordinates)
* @param opa_top opacity on the top
* @param y_top at which coordinate start to change to opacity to `opa_bottom`
* @param opa_bottom opacity at the bottom
* @param y_bottom at which coordinate reach `opa_bottom`.
*/
void lv_draw_sw_mask_fade_init(lv_draw_sw_mask_fade_param_t * param, const lv_area_t * coords, lv_opa_t opa_top,
int32_t y_top,
lv_opa_t opa_bottom, int32_t y_bottom);
/**
* Initialize a map mask.
* @param param pointer to a `lv_draw_mask_param_t` to initialize
* @param coords coordinates of the map (absolute coordinates)
* @param map array of bytes with the mask values
*/
void lv_draw_sw_mask_map_init(lv_draw_sw_mask_map_param_t * param, const lv_area_t * coords, const lv_opa_t * map);
#endif /*LV_DRAW_SW_COMPLEX*/
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_SW_MASK_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_fill.c | /**
* @file lv_draw_sw_fill.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_draw_sw.h"
#if LV_USE_DRAW_SW
#include "blend/lv_draw_sw_blend.h"
#include "lv_draw_sw_gradient.h"
#include "../../misc/lv_math.h"
#include "../../misc/lv_text_ap.h"
#include "../../core/lv_refr.h"
#include "../../misc/lv_assert.h"
#include "../../stdlib/lv_string.h"
#include "../lv_draw_mask.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_sw_fill(lv_draw_unit_t * draw_unit, const lv_draw_fill_dsc_t * dsc, const lv_area_t * coords)
{
if(dsc->opa <= LV_OPA_MIN) return;
lv_area_t bg_coords;
lv_area_copy(&bg_coords, coords);
lv_area_t clipped_coords;
if(!_lv_area_intersect(&clipped_coords, &bg_coords, draw_unit->clip_area)) return;
lv_grad_dir_t grad_dir = dsc->grad.dir;
lv_color_t bg_color = grad_dir == LV_GRAD_DIR_NONE ? dsc->color : dsc->grad.stops[0].color;
lv_draw_sw_blend_dsc_t blend_dsc = {0};
blend_dsc.color = bg_color;
/*Most simple case: just a plain rectangle*/
if(dsc->radius == 0 && (grad_dir == LV_GRAD_DIR_NONE)) {
blend_dsc.blend_area = &bg_coords;
blend_dsc.opa = dsc->opa;
lv_draw_sw_blend(draw_unit, &blend_dsc);
return;
}
/*Complex case: there is gradient, mask, or radius*/
#if LV_DRAW_SW_COMPLEX == 0
LV_LOG_WARN("Can't draw complex rectangle because LV_DRAW_SW_COMPLEX = 0");
#else
lv_opa_t opa = dsc->opa >= LV_OPA_MAX ? LV_OPA_COVER : dsc->opa;
/*Get the real radius. Can't be larger than the half of the shortest side */
int32_t coords_bg_w = lv_area_get_width(&bg_coords);
int32_t coords_bg_h = lv_area_get_height(&bg_coords);
int32_t short_side = LV_MIN(coords_bg_w, coords_bg_h);
int32_t rout = LV_MIN(dsc->radius, short_side >> 1);
/*Add a radius mask if there is a radius*/
int32_t clipped_w = lv_area_get_width(&clipped_coords);
lv_opa_t * mask_buf = NULL;
lv_draw_sw_mask_radius_param_t mask_rout_param;
void * mask_list[2] = {NULL, NULL};
if(rout > 0) {
mask_buf = lv_malloc(clipped_w);
lv_draw_sw_mask_radius_init(&mask_rout_param, &bg_coords, rout, false);
mask_list[0] = &mask_rout_param;
}
int32_t h;
lv_area_t blend_area;
blend_area.x1 = clipped_coords.x1;
blend_area.x2 = clipped_coords.x2;
blend_dsc.mask_buf = mask_buf;
blend_dsc.blend_area = &blend_area;
blend_dsc.mask_area = &blend_area;
blend_dsc.opa = LV_OPA_COVER;
/*Get gradient if appropriate*/
lv_grad_t * grad = lv_gradient_get(&dsc->grad, coords_bg_w, coords_bg_h);
lv_opa_t * grad_opa_map = NULL;
if(grad && grad_dir == LV_GRAD_DIR_HOR) {
blend_dsc.src_area = &blend_area;
blend_dsc.src_buf = grad->color_map + clipped_coords.x1 - bg_coords.x1;
bool transp = false;
uint32_t s;
for(s = 0; s < dsc->grad.stops_count; s++) {
if(dsc->grad.stops[s].opa != LV_OPA_COVER) {
transp = true;
break;
}
}
if(transp) grad_opa_map = grad->opa_map + clipped_coords.x1 - bg_coords.x1;
blend_dsc.src_color_format = LV_COLOR_FORMAT_RGB888;
}
/* Draw the top of the rectangle line by line and mirror it to the bottom. */
for(h = 0; h < rout; h++) {
int32_t top_y = bg_coords.y1 + h;
int32_t bottom_y = bg_coords.y2 - h;
if(top_y < clipped_coords.y1 && bottom_y > clipped_coords.y2) continue; /*This line is clipped now*/
/* Initialize the mask to opa instead of 0xFF and blend with LV_OPA_COVER.
* It saves calculating the final opa in lv_draw_sw_blend*/
lv_memset(mask_buf, opa, clipped_w);
blend_dsc.mask_res = lv_draw_sw_mask_apply(mask_list, mask_buf, blend_area.x1, top_y, clipped_w);
if(blend_dsc.mask_res == LV_DRAW_SW_MASK_RES_FULL_COVER) blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
if(top_y >= clipped_coords.y1) {
blend_area.y1 = top_y;
blend_area.y2 = top_y;
if(grad_dir == LV_GRAD_DIR_VER) {
blend_dsc.color = grad->color_map[top_y - bg_coords.y1];
blend_dsc.opa = grad->opa_map[top_y - bg_coords.y1];
}
else if(grad_dir == LV_GRAD_DIR_HOR) {
if(grad_opa_map) {
int32_t i;
for(i = 0; i < clipped_w; i++) {
if(grad_opa_map[i] < LV_OPA_MAX) mask_buf[i] = (mask_buf[i] * grad_opa_map[i]) >> 8;
}
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
}
}
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
if(bottom_y <= clipped_coords.y2) {
blend_area.y1 = bottom_y;
blend_area.y2 = bottom_y;
if(grad_dir == LV_GRAD_DIR_VER) {
blend_dsc.color = grad->color_map[bottom_y - bg_coords.y1];
blend_dsc.opa = grad->opa_map[bottom_y - bg_coords.y1];
}
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
}
/* Draw the center of the rectangle.*/
/*If no gradient, the center is a simple rectangle*/
if(grad_dir == LV_GRAD_DIR_NONE) {
blend_area.y1 = bg_coords.y1 + rout;
blend_area.y2 = bg_coords.y2 - rout;
blend_dsc.opa = opa;
blend_dsc.mask_buf = NULL;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
/*With gradient draw line by line*/
else {
blend_dsc.opa = opa;
if(grad_dir == LV_GRAD_DIR_VER) {
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_FULL_COVER;
}
else if(grad_dir == LV_GRAD_DIR_HOR) {
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
blend_dsc.mask_buf = grad_opa_map;
}
int32_t h_end = bg_coords.y2 - rout;
for(h = bg_coords.y1 + rout; h <= h_end; h++) {
blend_area.y1 = h;
blend_area.y2 = h;
if(grad_dir == LV_GRAD_DIR_VER) {
blend_dsc.color = grad->color_map[h - bg_coords.y1];
if(opa >= LV_OPA_MAX) blend_dsc.opa = grad->opa_map[h - bg_coords.y1];
else blend_dsc.opa = LV_OPA_MIX2(grad->opa_map[h - bg_coords.y1], opa);
}
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
}
if(mask_buf) {
lv_free(mask_buf);
lv_draw_sw_mask_free_param(&mask_rout_param);
}
if(grad) {
lv_gradient_cleanup(grad);
}
#endif
}
#endif /*LV_USE_DRAW_SW*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/lv_draw_sw_letter.c | /**
* @file lv_draw_sw_letter.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_draw_sw.h"
#if LV_USE_DRAW_SW
#include "../../display/lv_display.h"
#include "../../misc/lv_math.h"
#include "../../misc/lv_assert.h"
#include "../../misc/lv_area.h"
#include "../../misc/lv_style.h"
#include "../../font/lv_font.h"
#include "../../core/lv_refr.h"
#include "../../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
LV_ATTRIBUTE_FAST_MEM static void draw_letter_cb(lv_draw_unit_t * draw_unit, lv_draw_glyph_dsc_t * glyph_draw_dsc,
lv_draw_fill_dsc_t * fill_draw_dsc, const lv_area_t * fill_area);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* GLOBAL VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_sw_label(lv_draw_unit_t * draw_unit, const lv_draw_label_dsc_t * dsc, const lv_area_t * coords)
{
if(dsc->opa <= LV_OPA_MIN) return;
lv_draw_label_iterate_letters(draw_unit, dsc, coords, draw_letter_cb);
}
/**********************
* STATIC FUNCTIONS
**********************/
LV_ATTRIBUTE_FAST_MEM static void draw_letter_cb(lv_draw_unit_t * draw_unit, lv_draw_glyph_dsc_t * glyph_draw_dsc,
lv_draw_fill_dsc_t * fill_draw_dsc, const lv_area_t * fill_area)
{
if(glyph_draw_dsc) {
if(glyph_draw_dsc->bitmap == NULL) {
#if LV_USE_FONT_PLACEHOLDER
/* Draw a placeholder rectangle*/
lv_draw_border_dsc_t border_draw_dsc;
lv_draw_border_dsc_init(&border_draw_dsc);
border_draw_dsc.opa = glyph_draw_dsc->opa;
border_draw_dsc.color = glyph_draw_dsc->color;
border_draw_dsc.width = 1;
lv_draw_sw_border(draw_unit, &border_draw_dsc, glyph_draw_dsc->bg_coords);
#endif
}
else if(glyph_draw_dsc->format == LV_DRAW_LETTER_BITMAP_FORMAT_A8) {
lv_area_t mask_area = *glyph_draw_dsc->letter_coords;
mask_area.x2 = mask_area.x1 + lv_draw_buf_width_to_stride(lv_area_get_width(&mask_area), LV_COLOR_FORMAT_A8) - 1;
lv_draw_sw_blend_dsc_t blend_dsc;
lv_memzero(&blend_dsc, sizeof(blend_dsc));
blend_dsc.color = glyph_draw_dsc->color;
blend_dsc.opa = glyph_draw_dsc->opa;
blend_dsc.mask_buf = glyph_draw_dsc->bitmap;
blend_dsc.mask_area = &mask_area;
blend_dsc.blend_area = glyph_draw_dsc->letter_coords;
blend_dsc.mask_res = LV_DRAW_SW_MASK_RES_CHANGED;
lv_draw_sw_blend(draw_unit, &blend_dsc);
}
else if(glyph_draw_dsc->format == LV_DRAW_LETTER_BITMAP_FORMAT_IMAGE) {
#if LV_USE_IMGFONT
lv_draw_image_dsc_t img_dsc;
lv_draw_image_dsc_init(&img_dsc);
img_dsc.rotation = 0;
img_dsc.scale_x = LV_SCALE_NONE;
img_dsc.scale_y = LV_SCALE_NONE;
img_dsc.opa = glyph_draw_dsc->opa;
img_dsc.src = glyph_draw_dsc->bitmap;
lv_draw_sw_image(draw_unit, &img_dsc, glyph_draw_dsc->letter_coords);
#endif
}
}
if(fill_draw_dsc && fill_area) {
lv_draw_sw_fill(draw_unit, fill_draw_dsc, fill_area);
}
}
#endif /*LV_USE_DRAW_SW*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/blend/lv_draw_sw_blend_to_rgb888.h | /**
* @file lv_draw_sw_blend_rgb888.h
*
*/
#ifndef LV_DRAW_SW_BLEND_RGB888_H
#define LV_DRAW_SW_BLEND_RGB888_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_draw_sw.h"
#if LV_USE_DRAW_SW
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
LV_ATTRIBUTE_FAST_MEM void lv_draw_sw_blend_color_to_rgb888(_lv_draw_sw_blend_fill_dsc_t * dsc, uint32_t dest_px_size);
LV_ATTRIBUTE_FAST_MEM void lv_draw_sw_blend_image_to_rgb888(_lv_draw_sw_blend_image_dsc_t * dsc, uint32_t dest_px_size);
/**********************
* MACROS
**********************/
#endif /*LV_USE_DRAW_SW*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_SW_BLEND_RGB888_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/blend/lv_draw_sw_blend.c | /**
* @file lv_draw_sw_blend.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../lv_draw_sw.h"
#include "lv_draw_sw_blend_to_rgb565.h"
#include "lv_draw_sw_blend_to_argb8888.h"
#include "lv_draw_sw_blend_to_rgb888.h"
#if LV_USE_DRAW_SW
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_draw_sw_blend(lv_draw_unit_t * draw_unit, const lv_draw_sw_blend_dsc_t * blend_dsc)
{
/*Do not draw transparent things*/
if(blend_dsc->opa <= LV_OPA_MIN) return;
if(blend_dsc->mask_buf && blend_dsc->mask_res == LV_DRAW_SW_MASK_RES_TRANSP) return;
lv_area_t blend_area;
if(!_lv_area_intersect(&blend_area, blend_dsc->blend_area, draw_unit->clip_area)) return;
lv_layer_t * layer = draw_unit->target_layer;
uint32_t layer_stride_byte = lv_draw_buf_width_to_stride(lv_area_get_width(&layer->buf_area), layer->color_format);
uint32_t layer_stride_px = layer_stride_byte / lv_color_format_get_size(layer->color_format);
if(blend_dsc->src_buf == NULL) {
_lv_draw_sw_blend_fill_dsc_t fill_dsc;
fill_dsc.dest_w = lv_area_get_width(&blend_area);
fill_dsc.dest_h = lv_area_get_height(&blend_area);
fill_dsc.dest_stride = layer_stride_px;
fill_dsc.opa = blend_dsc->opa;
fill_dsc.color = blend_dsc->color;
if(blend_dsc->mask_buf == NULL) fill_dsc.mask_buf = NULL;
else if(blend_dsc->mask_res == LV_DRAW_SW_MASK_RES_FULL_COVER) fill_dsc.mask_buf = NULL;
else fill_dsc.mask_buf = blend_dsc->mask_buf;
fill_dsc.dest_buf = lv_draw_layer_go_to_xy(layer, blend_area.x1 - layer->buf_area.x1,
blend_area.y1 - layer->buf_area.y1);
if(fill_dsc.mask_buf) {
fill_dsc.mask_stride = blend_dsc->mask_stride == 0 ? lv_area_get_width(blend_dsc->mask_area) : blend_dsc->mask_stride;
fill_dsc.mask_buf += fill_dsc.mask_stride * (blend_area.y1 - blend_dsc->mask_area->y1) +
(blend_area.x1 - blend_dsc->mask_area->x1);
}
switch(layer->color_format) {
case LV_COLOR_FORMAT_RGB565:
lv_draw_sw_blend_color_to_rgb565(&fill_dsc);
break;
case LV_COLOR_FORMAT_ARGB8888:
lv_draw_sw_blend_color_to_argb8888(&fill_dsc);
break;
case LV_COLOR_FORMAT_RGB888:
lv_draw_sw_blend_color_to_rgb888(&fill_dsc, 3);
break;
case LV_COLOR_FORMAT_XRGB8888:
lv_draw_sw_blend_color_to_rgb888(&fill_dsc, 4);
break;
default:
break;
}
}
else {
if(!_lv_area_intersect(&blend_area, &blend_area, blend_dsc->src_area)) return;
_lv_draw_sw_blend_image_dsc_t image_dsc;
image_dsc.dest_w = lv_area_get_width(&blend_area);
image_dsc.dest_h = lv_area_get_height(&blend_area);
image_dsc.dest_stride = layer_stride_px;
image_dsc.opa = blend_dsc->opa;
image_dsc.blend_mode = blend_dsc->blend_mode;
image_dsc.src_stride = blend_dsc->src_stride / lv_color_format_get_size(blend_dsc->src_color_format);
image_dsc.src_color_format = blend_dsc->src_color_format;
const uint8_t * src_buf = blend_dsc->src_buf;
uint32_t src_px_size = lv_color_format_get_size(blend_dsc->src_color_format);
src_buf += image_dsc.src_stride * (blend_area.y1 - blend_dsc->src_area->y1) * src_px_size;
src_buf += (blend_area.x1 - blend_dsc->src_area->x1) * src_px_size;
image_dsc.src_buf = src_buf;
if(blend_dsc->mask_buf == NULL) image_dsc.mask_buf = NULL;
else if(blend_dsc->mask_res == LV_DRAW_SW_MASK_RES_FULL_COVER) image_dsc.mask_buf = NULL;
else image_dsc.mask_buf = blend_dsc->mask_buf;
if(image_dsc.mask_buf) {
image_dsc.mask_buf = blend_dsc->mask_buf;
image_dsc.mask_stride = lv_area_get_width(blend_dsc->mask_area);
image_dsc.mask_buf += image_dsc.mask_stride * (blend_area.y1 - blend_dsc->mask_area->y1) +
(blend_area.x1 - blend_dsc->mask_area->x1);
}
image_dsc.dest_buf = lv_draw_layer_go_to_xy(layer, blend_area.x1 - layer->buf_area.x1,
blend_area.y1 - layer->buf_area.y1);
switch(layer->color_format) {
case LV_COLOR_FORMAT_RGB565:
case LV_COLOR_FORMAT_RGB565A8:
lv_draw_sw_blend_image_to_rgb565(&image_dsc);
break;
case LV_COLOR_FORMAT_ARGB8888:
lv_draw_sw_blend_image_to_argb8888(&image_dsc);
break;
case LV_COLOR_FORMAT_RGB888:
lv_draw_sw_blend_image_to_rgb888(&image_dsc, 3);
break;
case LV_COLOR_FORMAT_XRGB8888:
lv_draw_sw_blend_image_to_rgb888(&image_dsc, 4);
break;
default:
break;
}
}
}
/**********************
* STATIC FUNCTIONS
**********************/
#endif
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/blend/lv_draw_sw_blend_to_rgb565.h | /**
* @file lv_draw_sw_blend_rgb565.h
*
*/
#ifndef LV_DRAW_SW_BLEND_RGB565_H
#define LV_DRAW_SW_BLEND_RGB565_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_draw_sw.h"
#if LV_USE_DRAW_SW
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
LV_ATTRIBUTE_FAST_MEM void lv_draw_sw_blend_color_to_rgb565(_lv_draw_sw_blend_fill_dsc_t * dsc);
LV_ATTRIBUTE_FAST_MEM void lv_draw_sw_blend_image_to_rgb565(_lv_draw_sw_blend_image_dsc_t * dsc);
/**********************
* MACROS
**********************/
#endif /*LV_USE_DRAW_SW*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_SW_BLEND_RGB565_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/blend/lv_draw_sw_blend.h | /**
* @file lv_draw_sw_blend.h
*
*/
#ifndef LV_DRAW_SW_BLEND_H
#define LV_DRAW_SW_BLEND_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_draw_sw_mask.h"
#if LV_USE_DRAW_SW
#include "../../../misc/lv_color.h"
#include "../../../misc/lv_area.h"
#include "../../../misc/lv_style.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
const lv_area_t * blend_area; /**< The area with absolute coordinates to draw on `layer->buf`
* will be clipped to `layer->clip_area` */
const void * src_buf; /**< Pointer to an image to blend. If set `fill_color` is ignored */
uint32_t src_stride;
lv_color_format_t src_color_format;
const lv_area_t * src_area;
lv_opa_t opa; /**< The overall opacity*/
lv_color_t color; /**< Fill color*/
const lv_opa_t * mask_buf; /**< NULL if ignored, or an alpha mask to apply on `blend_area`*/
lv_draw_sw_mask_res_t mask_res; /**< The result of the previous mask operation */
const lv_area_t * mask_area; /**< The area of `mask_buf` with absolute coordinates*/
int32_t mask_stride;
lv_blend_mode_t blend_mode; /**< E.g. LV_BLEND_MODE_ADDITIVE*/
} lv_draw_sw_blend_dsc_t;
struct _lv_draw_unit_t;
typedef struct {
void * dest_buf;
int32_t dest_w;
int32_t dest_h;
int32_t dest_stride;
const lv_opa_t * mask_buf;
int32_t mask_stride;
lv_color_t color;
lv_opa_t opa;
} _lv_draw_sw_blend_fill_dsc_t;
typedef struct {
void * dest_buf;
int32_t dest_w;
int32_t dest_h;
int32_t dest_stride;
const lv_opa_t * mask_buf;
int32_t mask_stride;
const void * src_buf;
int32_t src_stride;
lv_color_format_t src_color_format;
lv_opa_t opa;
lv_blend_mode_t blend_mode;
} _lv_draw_sw_blend_image_dsc_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Call the blend function of the `layer`.
* @param layer pointer to a draw context
* @param dsc pointer to an initialized blend descriptor
*/
void lv_draw_sw_blend(struct _lv_draw_unit_t * draw_unit, const lv_draw_sw_blend_dsc_t * dsc);
/**********************
* MACROS
**********************/
#endif /*LV_USE_DRAW_SW*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DRAW_SW_BLEND_H*/
|
0 | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw | repos/zig_workbench/BaseLVGL/lib/lvgl/src/draw/sw/blend/lv_draw_sw_blend_to_rgb565.c | /**
* @file lv_draw_sw_blend.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_draw_sw_blend_to_rgb565.h"
#if LV_USE_DRAW_SW
#include "lv_draw_sw_blend.h"
#include "../../../misc/lv_math.h"
#include "../../../display/lv_display.h"
#include "../../../core/lv_refr.h"
#include "../../../misc/lv_color.h"
#include "../../../stdlib/lv_string.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
LV_ATTRIBUTE_FAST_MEM static void rgb565_image_blend(_lv_draw_sw_blend_image_dsc_t * dsc);
LV_ATTRIBUTE_FAST_MEM static void rgb888_image_blend(_lv_draw_sw_blend_image_dsc_t * dsc, const uint8_t src_px_size);
LV_ATTRIBUTE_FAST_MEM static void argb8888_image_blend(_lv_draw_sw_blend_image_dsc_t * dsc);
LV_ATTRIBUTE_FAST_MEM static inline uint16_t lv_color_24_16_mix(const uint8_t * c1, uint16_t c2, uint8_t mix);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Fill an area with a color.
* Supports normal fill, fill with opacity, fill with mask, and fill with mask and opacity.
* dest_buf and color have native color depth. (RGB565, RGB888, XRGB8888)
* The background (dest_buf) cannot have alpha channel
* @param dest_buf
* @param dest_area
* @param dest_stride
* @param color
* @param opa
* @param mask
* @param mask_stride
*/
LV_ATTRIBUTE_FAST_MEM void lv_draw_sw_blend_color_to_rgb565(_lv_draw_sw_blend_fill_dsc_t * dsc)
{
int32_t w = dsc->dest_w;
int32_t h = dsc->dest_h;
uint16_t color16 = lv_color_to_u16(dsc->color);
lv_opa_t opa = dsc->opa;
const lv_opa_t * mask = dsc->mask_buf;
int32_t mask_stride = dsc->mask_stride;
uint16_t * dest_buf_u16 = dsc->dest_buf;
int32_t dest_stride = dsc->dest_stride;
int32_t x;
int32_t y;
/*Simple fill*/
if(mask == NULL && opa >= LV_OPA_MAX) {
for(y = 0; y < h; y++) {
uint16_t * dest_end_final = dest_buf_u16 + w;
uint32_t * dest_end_mid = (uint32_t *)((uint16_t *) dest_buf_u16 + ((w - 1) & ~(0xF)));
if((lv_uintptr_t)&dest_buf_u16[0] & 0x3) {
dest_buf_u16[0] = color16;
dest_buf_u16++;
}
uint32_t c32 = (uint32_t)color16 + ((uint32_t)color16 << 16);
uint32_t * dest32 = (uint32_t *)dest_buf_u16;
while(dest32 < dest_end_mid) {
dest32[0] = c32;
dest32[1] = c32;
dest32[2] = c32;
dest32[3] = c32;
dest32[4] = c32;
dest32[5] = c32;
dest32[6] = c32;
dest32[7] = c32;
dest32 += 8;
}
dest_buf_u16 = (uint16_t *)dest32;
while(dest_buf_u16 < dest_end_final) {
*dest_buf_u16 = color16;
dest_buf_u16++;
}
dest_buf_u16 += dest_stride - w;
}
}
/*Opacity only*/
else if(mask == NULL && opa < LV_OPA_MAX) {
uint32_t last_dest32_color = dest_buf_u16[0] + 1; /*Set to value which is not equal to the first pixel*/
uint32_t last_res32_color = 0;
for(y = 0; y < h; y++) {
x = 0;
if((lv_uintptr_t)&dest_buf_u16[0] & 0x3) {
dest_buf_u16[0] = lv_color_16_16_mix(color16, dest_buf_u16[0], opa);
x = 1;
}
for(; x < w - 2; x += 2) {
if(dest_buf_u16[x] != dest_buf_u16[x + 1]) {
dest_buf_u16[x + 0] = lv_color_16_16_mix(color16, dest_buf_u16[x + 0], opa);
dest_buf_u16[x + 1] = lv_color_16_16_mix(color16, dest_buf_u16[x + 1], opa);
}
else {
volatile uint32_t * dest32 = (uint32_t *)&dest_buf_u16[x];
if(last_dest32_color == *dest32) {
*dest32 = last_res32_color;
}
else {
last_dest32_color = *dest32;
dest_buf_u16[x] = lv_color_16_16_mix(color16, dest_buf_u16[x + 0], opa);
dest_buf_u16[x + 1] = dest_buf_u16[x];
last_res32_color = *dest32;
}
}
}
for(; x < w ; x++) {
dest_buf_u16[x] = lv_color_16_16_mix(color16, dest_buf_u16[x], opa);
}
dest_buf_u16 += dest_stride;
}
}
/*Masked with full opacity*/
else if(mask && opa >= LV_OPA_MAX) {
uint32_t c32 = color16 + ((uint32_t)color16 << 16);
for(y = 0; y < h; y++) {
for(x = 0; x < w && ((lv_uintptr_t)(mask) & 0x3); x++) {
dest_buf_u16[x] = lv_color_16_16_mix(color16, dest_buf_u16[x], mask[x]);
}
for(; x <= w - 4; x += 4) {
uint32_t mask32 = *((uint32_t *)&mask[x]);
if(mask32 == 0xFFFFFFFF) {
if((lv_uintptr_t)&dest_buf_u16[x] & 0x3) {
dest_buf_u16[x] = color16;
uint32_t * d32 = (uint32_t *)(&dest_buf_u16[x + 1]);
*d32 = c32;
dest_buf_u16[x + 3] = color16;
}
else {
uint32_t * dest32 = (uint32_t *)&dest_buf_u16[x];
dest32[0] = c32;
dest32[1] = c32;
}
}
else if(mask32) {
dest_buf_u16[x + 0] = lv_color_16_16_mix(color16, dest_buf_u16[x + 0], mask[x + 0]);
dest_buf_u16[x + 1] = lv_color_16_16_mix(color16, dest_buf_u16[x + 1], mask[x + 1]);
dest_buf_u16[x + 2] = lv_color_16_16_mix(color16, dest_buf_u16[x + 2], mask[x + 2]);
dest_buf_u16[x + 3] = lv_color_16_16_mix(color16, dest_buf_u16[x + 3], mask[x + 3]);
}
}
for(; x < w ; x++) {
dest_buf_u16[x] = lv_color_16_16_mix(color16, dest_buf_u16[x], mask[x]);
}
dest_buf_u16 += dest_stride;
mask += mask_stride;
}
}
/*Masked with opacity*/
else if(mask && opa < LV_OPA_MAX) {
for(y = 0; y < h; y++) {
for(x = 0; x < w; x++) {
dest_buf_u16[x] = lv_color_16_16_mix(color16, dest_buf_u16[x], LV_OPA_MIX2(mask[x], opa));
}
dest_buf_u16 += dest_stride;
mask += mask_stride;
}
}
}
LV_ATTRIBUTE_FAST_MEM void lv_draw_sw_blend_image_to_rgb565(_lv_draw_sw_blend_image_dsc_t * dsc)
{
switch(dsc->src_color_format) {
case LV_COLOR_FORMAT_RGB565:
rgb565_image_blend(dsc);
break;
case LV_COLOR_FORMAT_RGB888:
rgb888_image_blend(dsc, 3);
break;
case LV_COLOR_FORMAT_XRGB8888:
rgb888_image_blend(dsc, 4);
break;
case LV_COLOR_FORMAT_ARGB8888:
argb8888_image_blend(dsc);
break;
default:
LV_LOG_WARN("Not supported source color format");
break;
}
}
/**********************
* STATIC FUNCTIONS
**********************/
LV_ATTRIBUTE_FAST_MEM static void rgb565_image_blend(_lv_draw_sw_blend_image_dsc_t * dsc)
{
int32_t w = dsc->dest_w;
int32_t h = dsc->dest_h;
lv_opa_t opa = dsc->opa;
uint16_t * dest_buf_u16 = dsc->dest_buf;
int32_t dest_stride = dsc->dest_stride;
const uint16_t * src_buf_u16 = dsc->src_buf;
int32_t src_stride = dsc->src_stride;
const lv_opa_t * mask_buf = dsc->mask_buf;
int32_t mask_stride = dsc->mask_stride;
int32_t x;
int32_t y;
if(dsc->blend_mode == LV_BLEND_MODE_NORMAL) {
if(mask_buf == NULL && opa >= LV_OPA_MAX) {
uint32_t line_in_bytes = w * 2;
for(y = 0; y < h; y++) {
lv_memcpy(dest_buf_u16, src_buf_u16, line_in_bytes);
dest_buf_u16 += dest_stride;
src_buf_u16 += src_stride;
}
}
else if(mask_buf == NULL && opa < LV_OPA_MAX) {
for(y = 0; y < h; y++) {
for(x = 0; x < w; x++) {
dest_buf_u16[x] = lv_color_16_16_mix(src_buf_u16[x], dest_buf_u16[x], opa);
}
dest_buf_u16 += dest_stride;
src_buf_u16 += src_stride;
}
}
else if(mask_buf && opa >= LV_OPA_MAX) {
for(y = 0; y < h; y++) {
for(x = 0; x < w; x++) {
dest_buf_u16[x] = lv_color_16_16_mix(src_buf_u16[x], dest_buf_u16[x], mask_buf[x]);
}
dest_buf_u16 += dest_stride;
src_buf_u16 += src_stride;
mask_buf += mask_stride;
}
}
else {
for(y = 0; y < h; y++) {
for(x = 0; x < w; x++) {
dest_buf_u16[x] = lv_color_16_16_mix(src_buf_u16[x], dest_buf_u16[x], LV_OPA_MIX2(mask_buf[x], opa));
}
dest_buf_u16 += dest_stride;
src_buf_u16 += src_stride;
mask_buf += mask_stride;
}
}
}
else {
lv_color16_t * dest_buf_c16 = (lv_color16_t *) dest_buf_u16;
lv_color16_t * src_buf_c16 = (lv_color16_t *) src_buf_u16;
uint16_t res = 0;
for(y = 0; y < h; y++) {
for(x = 0; x < w; x++) {
switch(dsc->blend_mode) {
case LV_BLEND_MODE_ADDITIVE:
if(src_buf_u16[x] == 0x0000) continue; /*Do not add pure black*/
res = LV_MIN(dest_buf_c16[x].red + src_buf_c16[x].red, 31);
res += LV_MIN(dest_buf_c16[x].green + src_buf_c16[x].green, 63);
res += LV_MIN(dest_buf_c16[x].blue + src_buf_c16[x].blue, 31);
break;
case LV_BLEND_MODE_SUBTRACTIVE:
if(src_buf_u16[x] == 0x0000) continue; /*Do not subtract pure black*/
res = LV_MAX(dest_buf_c16[x].red - src_buf_c16[x].red, 0);
res += LV_MAX(dest_buf_c16[x].green - src_buf_c16[x].green, 0);
res += LV_MAX(dest_buf_c16[x].blue - src_buf_c16[x].blue, 0);
break;
case LV_BLEND_MODE_MULTIPLY:
if(src_buf_u16[x] == 0xffff) continue; /*Do not multiply with pure white (considered as 1)*/
res = (dest_buf_c16[x].red * src_buf_c16[x].red) >> 5;
res += (dest_buf_c16[x].green * src_buf_c16[x].green) >> 6;
res += (dest_buf_c16[x].blue * src_buf_c16[x].blue) >> 5;
break;
default:
LV_LOG_WARN("Not supported blend mode: %d", dsc->blend_mode);
return;
}
if(mask_buf == NULL) {
lv_color_16_16_mix(res, dest_buf_u16[x], opa);
}
else {
if(opa >= LV_OPA_MAX) dest_buf_u16[x] = lv_color_16_16_mix(res, dest_buf_u16[x], mask_buf[x]);
else dest_buf_u16[x] = lv_color_16_16_mix(res, dest_buf_u16[x], LV_OPA_MIX2(mask_buf[x], opa));
}
}
dest_buf_u16 += dest_stride;
src_buf_u16 += src_stride;
if(mask_buf) mask_buf += mask_stride;
}
}
}
LV_ATTRIBUTE_FAST_MEM static void rgb888_image_blend(_lv_draw_sw_blend_image_dsc_t * dsc, const uint8_t src_px_size)
{
int32_t w = dsc->dest_w;
int32_t h = dsc->dest_h;
lv_opa_t opa = dsc->opa;
uint16_t * dest_buf_u16 = dsc->dest_buf;
int32_t dest_stride = dsc->dest_stride;
const uint8_t * src_buf_u8 = dsc->src_buf;
int32_t src_stride = dsc->src_stride * src_px_size;
const lv_opa_t * mask_buf = dsc->mask_buf;
int32_t mask_stride = dsc->mask_stride;
int32_t dest_x;
int32_t src_x;
int32_t y;
if(dsc->blend_mode == LV_BLEND_MODE_NORMAL) {
if(mask_buf == NULL && opa >= LV_OPA_MAX) {
for(y = 0; y < h; y++) {
for(dest_x = 0, src_x = 0; dest_x < w; dest_x++, src_x += src_px_size) {
dest_buf_u16[dest_x] = ((src_buf_u8[src_x + 2] & 0xF8) << 8) +
((src_buf_u8[src_x + 1] & 0xFC) << 3) +
((src_buf_u8[src_x + 0] & 0xF8) >> 3);
}
dest_buf_u16 += dest_stride;
src_buf_u8 += src_stride;
}
}
else if(mask_buf == NULL && opa < LV_OPA_MAX) {
for(y = 0; y < h; y++) {
for(dest_x = 0, src_x = 0; dest_x < w; dest_x++, src_x += src_px_size) {
dest_buf_u16[dest_x] = lv_color_24_16_mix(&src_buf_u8[src_x], dest_buf_u16[dest_x], opa);
}
dest_buf_u16 += dest_stride;
src_buf_u8 += src_stride;
}
}
if(mask_buf && opa >= LV_OPA_MAX) {
for(y = 0; y < h; y++) {
for(dest_x = 0, src_x = 0; dest_x < w; dest_x++, src_x += src_px_size) {
dest_buf_u16[dest_x] = lv_color_24_16_mix(&src_buf_u8[src_x], dest_buf_u16[dest_x], mask_buf[dest_x]);
}
dest_buf_u16 += dest_stride;
src_buf_u8 += src_stride;
mask_buf += mask_stride;
}
}
if(mask_buf && opa < LV_OPA_MAX) {
for(y = 0; y < h; y++) {
for(dest_x = 0, src_x = 0; dest_x < w; dest_x++, src_x += src_px_size) {
dest_buf_u16[dest_x] = lv_color_24_16_mix(&src_buf_u8[src_x], dest_buf_u16[dest_x], LV_OPA_MIX2(mask_buf[dest_x], opa));
}
dest_buf_u16 += dest_stride;
src_buf_u8 += src_stride;
mask_buf += mask_stride;
}
}
}
else {
lv_color16_t * dest_buf_c16 = (lv_color16_t *) dest_buf_u16;
uint16_t res = 0;
for(y = 0; y < h; y++) {
for(dest_x = 0, src_x = 0; dest_x < w; dest_x++, src_x += src_px_size) {
switch(dsc->blend_mode) {
case LV_BLEND_MODE_ADDITIVE:
res = LV_MIN(dest_buf_c16[dest_x].red + (src_buf_u8[src_x + 0] >> 3), 31);
res += LV_MIN(dest_buf_c16[dest_x].green + (src_buf_u8[src_x + 1] >> 2), 63);
res += LV_MIN(dest_buf_c16[dest_x].blue + (src_buf_u8[src_x + 2] >> 3), 31);
break;
case LV_BLEND_MODE_SUBTRACTIVE:
res = LV_MAX(dest_buf_c16[dest_x].red - (src_buf_u8[src_x + 0] >> 3), 0);
res += LV_MAX(dest_buf_c16[dest_x].green - (src_buf_u8[src_x + 1] >> 2), 0);
res += LV_MAX(dest_buf_c16[dest_x].blue - (src_buf_u8[src_x + 2] >> 3), 0);
break;
case LV_BLEND_MODE_MULTIPLY:
res = (dest_buf_c16[dest_x].red * (src_buf_u8[src_x + 0] >> 3)) >> 5;
res += (dest_buf_c16[dest_x].green * (src_buf_u8[src_x + 1] >> 2)) >> 6;
res += (dest_buf_c16[dest_x].blue * (src_buf_u8[src_x + 2] >> 3)) >> 5;
break;
default:
LV_LOG_WARN("Not supported blend mode: %d", dsc->blend_mode);
return;
}
if(mask_buf == NULL) {
lv_color_16_16_mix(res, dest_buf_u16[dest_x], opa);
}
else {
if(opa >= LV_OPA_MAX) dest_buf_u16[dest_x] = lv_color_16_16_mix(res, dest_buf_u16[dest_x], mask_buf[dest_x]);
else dest_buf_u16[dest_x] = lv_color_16_16_mix(res, dest_buf_u16[dest_x], LV_OPA_MIX2(mask_buf[dest_x], opa));
}
}
}
dest_buf_u16 += dest_stride;
src_buf_u8 += src_stride;
if(mask_buf) mask_buf += mask_stride;
}
}
LV_ATTRIBUTE_FAST_MEM static void argb8888_image_blend(_lv_draw_sw_blend_image_dsc_t * dsc)
{
int32_t w = dsc->dest_w;
int32_t h = dsc->dest_h;
lv_opa_t opa = dsc->opa;
uint16_t * dest_buf_u16 = dsc->dest_buf;
int32_t dest_stride = dsc->dest_stride;
const uint8_t * src_buf_u8 = dsc->src_buf;
int32_t src_stride = dsc->src_stride * 4;
const lv_opa_t * mask_buf = dsc->mask_buf;
int32_t mask_stride = dsc->mask_stride;
int32_t dest_x;
int32_t src_x;
int32_t y;
if(dsc->blend_mode == LV_BLEND_MODE_NORMAL) {
if(mask_buf == NULL && opa >= LV_OPA_MAX) {
for(y = 0; y < h; y++) {
for(dest_x = 0, src_x = 0; dest_x < w; dest_x++, src_x += 4) {
dest_buf_u16[dest_x] = lv_color_24_16_mix(&src_buf_u8[src_x], dest_buf_u16[dest_x], src_buf_u8[src_x + 3]);
}
dest_buf_u16 += dest_stride;
src_buf_u8 += src_stride;
}
}
else if(mask_buf == NULL && opa < LV_OPA_MAX) {
for(y = 0; y < h; y++) {
for(dest_x = 0, src_x = 0; dest_x < w; dest_x++, src_x += 4) {
dest_buf_u16[dest_x] = lv_color_24_16_mix(&src_buf_u8[src_x], dest_buf_u16[dest_x], LV_OPA_MIX2(src_buf_u8[src_x + 3],
opa));
}
dest_buf_u16 += dest_stride;
src_buf_u8 += src_stride;
}
}
else if(mask_buf && opa >= LV_OPA_MAX) {
for(y = 0; y < h; y++) {
for(dest_x = 0, src_x = 0; dest_x < w; dest_x++, src_x += 4) {
dest_buf_u16[dest_x] = lv_color_24_16_mix(&src_buf_u8[src_x], dest_buf_u16[dest_x],
LV_OPA_MIX2(src_buf_u8[src_x + 3], mask_buf[dest_x]));
}
dest_buf_u16 += dest_stride;
src_buf_u8 += src_stride;
mask_buf += mask_stride;
}
}
else if(mask_buf && opa < LV_OPA_MAX) {
for(y = 0; y < h; y++) {
for(dest_x = 0, src_x = 0; dest_x < w; dest_x++, src_x += 4) {
dest_buf_u16[dest_x] = lv_color_24_16_mix(&src_buf_u8[src_x], dest_buf_u16[dest_x],
LV_OPA_MIX3(src_buf_u8[src_x + 3], mask_buf[dest_x], opa));
}
dest_buf_u16 += dest_stride;
src_buf_u8 += src_stride;
mask_buf += mask_stride;
}
}
}
else {
lv_color16_t * dest_buf_c16 = (lv_color16_t *) dest_buf_u16;
uint16_t res = 0;
for(y = 0; y < h; y++) {
for(dest_x = 0, src_x = 0; dest_x < w; dest_x++, src_x += 4) {
switch(dsc->blend_mode) {
case LV_BLEND_MODE_ADDITIVE:
res = LV_MIN(dest_buf_c16[dest_x].red + (src_buf_u8[src_x + 0] >> 3), 31);
res += LV_MIN(dest_buf_c16[dest_x].green + (src_buf_u8[src_x + 1] >> 2), 63);
res += LV_MIN(dest_buf_c16[dest_x].blue + (src_buf_u8[src_x + 2] >> 3), 31);
break;
case LV_BLEND_MODE_SUBTRACTIVE:
res = LV_MAX(dest_buf_c16[dest_x].red - (src_buf_u8[src_x + 0] >> 3), 0);
res += LV_MAX(dest_buf_c16[dest_x].green - (src_buf_u8[src_x + 1] >> 2), 0);
res += LV_MAX(dest_buf_c16[dest_x].blue - (src_buf_u8[src_x + 2] >> 3), 0);
break;
case LV_BLEND_MODE_MULTIPLY:
res = (dest_buf_c16[dest_x].red * (src_buf_u8[src_x + 0] >> 3)) >> 5;
res += (dest_buf_c16[dest_x].green * (src_buf_u8[src_x + 1] >> 2)) >> 6;
res += (dest_buf_c16[dest_x].blue * (src_buf_u8[src_x + 2] >> 3)) >> 5;
break;
default:
LV_LOG_WARN("Not supported blend mode: %d", dsc->blend_mode);
return;
}
if(mask_buf == NULL && opa >= LV_OPA_MAX) {
lv_color_16_16_mix(res, dest_buf_u16[dest_x], src_buf_u8[src_x + 3]);
}
else if(mask_buf == NULL && opa < LV_OPA_MAX) {
lv_color_16_16_mix(res, dest_buf_u16[dest_x], LV_OPA_MIX2(opa, src_buf_u8[src_x + 3]));
}
else {
if(opa >= LV_OPA_MAX) dest_buf_u16[dest_x] = lv_color_16_16_mix(res, dest_buf_u16[dest_x], mask_buf[dest_x]);
else dest_buf_u16[dest_x] = lv_color_16_16_mix(res, dest_buf_u16[dest_x], LV_OPA_MIX3(mask_buf[dest_x], opa,
src_buf_u8[src_x + 3]));
}
}
dest_buf_u16 += dest_stride;
src_buf_u8 += src_stride;
if(mask_buf) mask_buf += mask_stride;
}
}
}
LV_ATTRIBUTE_FAST_MEM static inline uint16_t lv_color_24_16_mix(const uint8_t * c1, uint16_t c2, uint8_t mix)
{
if(mix == 0) {
return c2;
}
else if(mix == 255) {
return ((c1[2] & 0xF8) << 8) + ((c1[1] & 0xFC) << 3) + ((c1[0] & 0xF8) >> 3);
}
else {
lv_opa_t mix_inv = 255 - mix;
return ((((c1[2] >> 3) * mix + ((c2 >> 11) & 0x1F) * mix_inv) << 3) & 0xF800) +
((((c1[1] >> 2) * mix + ((c2 >> 5) & 0x3F) * mix_inv) >> 3) & 0x07E0) +
(((c1[0] >> 3) * mix + (c2 & 0x1F) * mix_inv) >> 8);
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.