Compare commits

...

9 Commits

Author SHA1 Message Date
phyxl
390a7053b8
Merge d7104efa69 into afba9f0de6 2025-01-13 17:21:39 +03:00
Harrison Lambeth
afba9f0de6
Add a function to reset text measurement cache (#181)
Some checks failed
CMake on multiple platforms / build (Release, cl, cl, windows-latest) (push) Waiting to run
CMake on multiple platforms / build (Release, clang, clang++, ubuntu-latest) (push) Failing after 14s
CMake on multiple platforms / build (Release, gcc, g++, ubuntu-latest) (push) Failing after 14s
2025-01-13 19:26:46 +13:00
Nic Barker
3a4455aa83
Fix text wrapping handling with explicit newline characters (#192)
Co-authored-by: Ryzee119 <wendland@live.com.au>
2025-01-13 19:23:28 +13:00
phyxl
d7104efa69
Merge branch 'main' into feature/terminal-renderer 2025-01-11 22:01:09 -05:00
Phillip Cook
c8341dc0a8 fix typo, remove generated Makefile, correct CMakeLists 2025-01-05 22:22:44 -05:00
Phillip Cook
244395edde rename to ncurses to follow convention, clean up checked in files 2025-01-05 22:19:03 -05:00
Phillip Cook
b0b0e15df5 clean up some files 2025-01-05 21:48:00 -05:00
Phillip Cook
286c0753fd Merge branch 'main' into feature/terminal-renderer 2025-01-05 21:40:03 -05:00
Phillip Cook
77d3fc4e82 implemented ncurses termninal renderer 2025-01-05 21:38:02 -05:00
8 changed files with 528 additions and 6 deletions

View File

@ -9,6 +9,7 @@ add_subdirectory("examples/raylib-sidebar-scrolling-container")
# add_subdirectory("examples/cairo-pdf-rendering") Some issue with github actions populating cairo, disable for now
if(NOT MSVC)
add_subdirectory("examples/clay-official-website")
add_subdirectory("examples/ncurses-sidebar-scrolling-container")
endif()
add_subdirectory("examples/introducing-clay-video-demo")
add_subdirectory("examples/SDL2-video-demo")

View File

@ -173,9 +173,12 @@ For help starting out or to discuss clay, considering joining [the discord serve
- [Clay_MinMemorySize](#clay_minmemorysize)
- [Clay_CreateArenaWithCapacityAndMemory](#clay_createarenawithcapacityandmemory)
- [Clay_SetMeasureTextFunction](#clay_setmeasuretextfunction)
- [Clay_ResetMeasureTextCache](#clau_resetmeasuretextcache)
- [Clay_SetMaxElementCount](clay_setmaxelementcount)
- [Clay_SetMaxMeasureTextCacheWordCount](#clay_setmaxmeasuretextcachewordcount)
- [Clay_Initialize](#clay_initialize)
- [Clay_GetCurrentContext](#clay_getcurrentcontext)
- [Clay_SetCurrentContext](#clay_setcurrentcontext)
- [Clay_SetLayoutDimensions](#clay_setlayoutdimensions)
- [Clay_SetPointerState](#clay_setpointerstate)
- [Clay_UpdateScrollContainers](#clay_updatescrollcontainers)
@ -575,6 +578,14 @@ Takes a pointer to a function that can be used to measure the `width, height` di
---
### Clay_ResetMeasureTextCache
`void Clay_ResetMeasureTextCache(void)`
Clay caches measurements from the provided MeasureTextFunction, and this will be sufficient for the majority of use-cases. However, if the measurements can depend on external factors that clay does not know about, like DPI changes, then the cached values may be incorrect. When one of these external factors changes, Clay_ResetMeasureTextCache can be called to force clay to recalculate all string measurements in the next frame.
---
### Clay_SetMaxElementCount
`void Clay_SetMaxElementCount(uint32_t maxElementCount)`
@ -603,12 +614,16 @@ Initializes the internal memory mapping, sets the internal dimensions for layout
Reference: [Clay_Arena](#clay_createarenawithcapacityandmemory), [Clay_ErrorHandler](#clay_errorhandler), [Clay_SetCurrentContext](#clay_setcurrentcontext)
---
### Clay_SetCurrentContext
`void Clay_SetCurrentContext(Clay_Context* context)`
Sets the context that subsequent clay commands will operate on. You can get this reference from [Clay_Initialize](#clay_initialize) or [Clay_GetCurrentContext](#clay_getcurrentcontext). See [Running more than one Clay instance](#running-more-than-one-clay-instance).
---
### Clay_GetCurrentContext
`Clay_Context* Clay_GetCurrentContext()`

36
clay.h
View File

@ -525,6 +525,7 @@ int32_t Clay_GetMaxElementCount(void);
void Clay_SetMaxElementCount(int32_t maxElementCount);
int32_t Clay_GetMaxMeasureTextCacheWordCount(void);
void Clay_SetMaxMeasureTextCacheWordCount(int32_t maxMeasureTextCacheWordCount);
void Clay_ResetMeasureTextCache(void);
// Internal API functions required by macros
void Clay__OpenElement(void);
@ -1213,6 +1214,7 @@ Clay__MeasuredWord *Clay__MeasuredWordArray_Add(Clay__MeasuredWordArray *array,
CLAY__TYPEDEF(Clay__MeasureTextCacheItem, struct {
Clay_Dimensions unwrappedDimensions;
int32_t measuredWordsStartIndex;
bool containsNewlines;
// Hash map data
uint32_t id;
int32_t nextIndex;
@ -1678,6 +1680,7 @@ Clay__MeasureTextCacheItem *Clay__MeasureTextCached(Clay_String *text, Clay_Text
int32_t start = 0;
int32_t end = 0;
float lineWidth = 0;
float measuredWidth = 0;
float measuredHeight = 0;
float spaceWidth = Clay__MeasureText(&CLAY__SPACECHAR, config).width;
@ -1699,18 +1702,22 @@ Clay__MeasureTextCacheItem *Clay__MeasureTextCached(Clay_String *text, Clay_Text
int32_t length = end - start;
Clay_String word = { .length = length, .chars = &text->chars[start] };
Clay_Dimensions dimensions = Clay__MeasureText(&word, config);
measuredHeight = CLAY__MAX(measuredHeight, dimensions.height);
if (current == ' ') {
dimensions.width += spaceWidth;
previousWord = Clay__AddMeasuredWord(CLAY__INIT(Clay__MeasuredWord) { .startOffset = start, .length = length + 1, .width = dimensions.width, .next = -1 }, previousWord);
lineWidth += dimensions.width;
}
if (current == '\n') {
if (length > 1) {
if (length > 0) {
previousWord = Clay__AddMeasuredWord(CLAY__INIT(Clay__MeasuredWord) { .startOffset = start, .length = length, .width = dimensions.width, .next = -1 }, previousWord);
}
previousWord = Clay__AddMeasuredWord(CLAY__INIT(Clay__MeasuredWord) { .startOffset = end + 1, .length = 0, .width = 0, .next = -1 }, previousWord);
lineWidth += dimensions.width;
measuredWidth = CLAY__MAX(lineWidth, measuredWidth);
measured->containsNewlines = true;
lineWidth = 0;
}
measuredWidth += dimensions.width;
measuredHeight = dimensions.height;
start = end + 1;
}
end++;
@ -1719,9 +1726,11 @@ Clay__MeasureTextCacheItem *Clay__MeasureTextCached(Clay_String *text, Clay_Text
Clay_String lastWord = { .length = end - start, .chars = &text->chars[start] };
Clay_Dimensions dimensions = Clay__MeasureText(&lastWord, config);
Clay__AddMeasuredWord(CLAY__INIT(Clay__MeasuredWord) { .startOffset = start, .length = end - start, .width = dimensions.width, .next = -1 }, previousWord);
measuredWidth += dimensions.width;
measuredHeight = dimensions.height;
lineWidth += dimensions.width;
measuredHeight = CLAY__MAX(measuredHeight, dimensions.height);
}
measuredWidth = CLAY__MAX(lineWidth, measuredWidth);
measured->measuredWordsStartIndex = tempWord.next;
measured->unwrappedDimensions.width = measuredWidth;
measured->unwrappedDimensions.height = measuredHeight;
@ -2367,7 +2376,7 @@ void Clay__CalculateFinalLayout() {
float lineHeight = textConfig->lineHeight > 0 ? (float)textConfig->lineHeight : textElementData->preferredDimensions.height;
int32_t lineLengthChars = 0;
int32_t lineStartOffset = 0;
if (textElementData->preferredDimensions.width <= containerElement->dimensions.width) {
if (!measureTextCacheItem->containsNewlines && textElementData->preferredDimensions.width <= containerElement->dimensions.width) {
Clay__WrappedTextLineArray_Add(&context->wrappedTextLines, CLAY__INIT(Clay__WrappedTextLine) { containerElement->dimensions, textElementData->text });
textElementData->wrappedLines.length++;
continue;
@ -4043,6 +4052,21 @@ void Clay_SetMaxMeasureTextCacheWordCount(int32_t maxMeasureTextCacheWordCount)
}
}
CLAY_WASM_EXPORT("Clay_ResetMeasureTextCache")
void Clay_ResetMeasureTextCache(void) {
Clay_Context* context = Clay_GetCurrentContext();
context->measureTextHashMapInternal.length = 0;
context->measureTextHashMapInternalFreeList.length = 0;
context->measureTextHashMap.length = 0;
context->measuredWords.length = 0;
context->measuredWordsFreeList.length = 0;
for (int32_t i = 0; i < context->measureTextHashMap.capacity; ++i) {
context->measureTextHashMap.internalArray[i] = 0;
}
context->measureTextHashMapInternal.length = 1; // Reserve the 0 value to mean "no next element"
}
#endif // CLAY_IMPLEMENTATION
/*

View File

@ -0,0 +1,18 @@
cmake_minimum_required(VERSION 3.27)
project(clay_examples_textui_sidebar_scrolling_container C)
set(CMAKE_C_STANDARD 99)
add_executable(clay_examples_textui_sidebar_scrolling_container main.c multi-compilation-unit.c)
target_compile_options(clay_examples_textui_sidebar_scrolling_container PUBLIC)
target_include_directories(clay_examples_textui_sidebar_scrolling_container PUBLIC .)
target_link_libraries(clay_examples_textui_sidebar_scrolling_container PUBLIC ncurses)
set(CMAKE_CXX_FLAGS_DEBUG "-Wall -Werror -DCLAY_DEBUG")
set(CMAKE_CXX_FLAGS_RELEASE "-O3")
add_custom_command(
TARGET clay_examples_textui_sidebar_scrolling_container POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_CURRENT_SOURCE_DIR}/resources
${CMAKE_CURRENT_BINARY_DIR}/resources)

View File

@ -0,0 +1,39 @@
# textui/console renderer example
## Introduction
This renderer example utilizes ncurses and a mostly implemented library which converts the clay draw commands into ncurses commands.
A console rendering is very limited, and all coordinates are simply rounded via integer division to the coordinate system of a terminal.
## What works
- Rectangles draw approximately correctly with the right color
- Text wraps, and is well placed
- Clicking a location on a scroll bar moves the scrolled area
- Debug mode highlights on click
- Window resize and layout reaction
## What doesn't work
- Image rendering
- Sub character rectangles
- Text fonts and colors
- Clay extensions
- Clay scissor mode
## Reasonable expectations
This renderer is intended to allow for a nearly dependency free implementation of Clay, and nearly all linux distributions have ncurses installed.
This renderer will allow for quick visualization of layouts. There is no graphics acceleration though this example is quite responsive.
The unit of a terminal is a character, not a pixel, so there is only so much detail that can be rendered. The default character size defined in the renderer is 5x8 pixels.
## What could work
- More precise rendering of borders and rectangles, this could be implemented with box-drawing characters: https://en.wikipedia.org/wiki/Box-drawing_characters
- The mouse wheel on some terminals
- Images with an additional dependency on something like kitty: https://sw.kovidgoyal.net/kitty/graphics-protocol/
- Better text coloring by matching the background
## Setup
You'll have to setup an event loop using getch(), and pay attention to the various init functions in main.c
Then it's the regular Clay layout definition and calls to the renderer function.
## Conclusion
The truth is that if you're willing to learn ncurses and how it handles windows you can get a better terminal experience without Clay.
This example shows that for quick terminal apps, Clay could be extremely effective for organizing a user interface in the terminal.
I hope that this renderer helps many people build fun and cool projects by lowering the barrier to a framwork.

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,9 @@
#include "../../clay.h"
// NOTE: This file only exists to make sure that clay works when included in multiple translation units.
void SatisfyCompiler() {
CLAY(CLAY_ID("SatisfyCompiler"), CLAY_LAYOUT({})) {
CLAY_TEXT(CLAY_STRING("Test"), CLAY_TEXT_CONFIG({ .fontId = 0, .fontSize = 24 }));
}
}

View File

@ -0,0 +1,129 @@
//#include <stdio.h>
#include <curses.h>
#define CLAY_IMPLEMENTATION
#include "../../clay.h"
#define HPIXELS_PER_CHAR 5 //these are used to convert between Clay pixel space and terminal character locations
#define VPIXELS_PER_CHAR 8
void Clay_ncurses_Render(WINDOW * win, Clay_RenderCommandArray renderCommands);
void Clay_ncurses_Render(WINDOW * win, Clay_RenderCommandArray renderCommands){
short color_pair = 1; //increment on use, 0 is reserved
short color = 10; //get passed reserved colors
//maybe keep a list of Clay colors and only init a new color if required.
//clear the screen/window
clear();//sets cursor to 0,0
for(int i = 0; i < renderCommands.length; i++){
//handle every command
switch (renderCommands.internalArray[i].commandType){
case CLAY_RENDER_COMMAND_TYPE_NONE:
continue;
case CLAY_RENDER_COMMAND_TYPE_RECTANGLE:
Clay_RectangleElementConfig *rectangle_config = renderCommands.internalArray[i].config.rectangleElementConfig;
init_color(color, rectangle_config->color.r, rectangle_config->color.g, rectangle_config->color.b);
init_pair(color_pair, color, color);
attr_on(color_set(color_pair,0),0);
for(int j = 0; j < renderCommands.internalArray[i].boundingBox.height/VPIXELS_PER_CHAR; j++){
mvhline(renderCommands.internalArray[i].boundingBox.y/VPIXELS_PER_CHAR + j, renderCommands.internalArray[i].boundingBox.x/HPIXELS_PER_CHAR, '#', renderCommands.internalArray[i].boundingBox.width/HPIXELS_PER_CHAR);
}
attr_off(color_set(color_pair,0),0);
color_pair++;
color++;
//TODO render radius corners
break;
case CLAY_RENDER_COMMAND_TYPE_BORDER:
Clay_BorderElementConfig *border_config = renderCommands.internalArray[i].config.borderElementConfig;
//just get a border on there for now
if(border_config->top.width > 0){
init_color(color, border_config->top.color.r, border_config->top.color.g, border_config->top.color.b);
init_pair(color_pair, color, COLOR_CYAN);//TODO get color at target location and init pair with that background
attr_on(color_set(color_pair,0),0);
mvhline(renderCommands.internalArray[i].boundingBox.y/VPIXELS_PER_CHAR, renderCommands.internalArray[i].boundingBox.x/HPIXELS_PER_CHAR + 1, '-', renderCommands.internalArray[i].boundingBox.width/HPIXELS_PER_CHAR - 2);
attr_off(color_set(color_pair,0),0);
color_pair++; //can we just check of the color requested is already there?
color++;
}
if(border_config->bottom.width > 0){
init_color(color, border_config->bottom.color.r, border_config->bottom.color.g, border_config->bottom.color.b);
init_pair(color_pair, color, COLOR_CYAN);//TODO get color at target location and init pair with that background
attr_on(color_set(color_pair,0),0);
mvhline(renderCommands.internalArray[i].boundingBox.y/VPIXELS_PER_CHAR + renderCommands.internalArray[i].boundingBox.height/VPIXELS_PER_CHAR, renderCommands.internalArray[i].boundingBox.x/HPIXELS_PER_CHAR + 1, '-', renderCommands.internalArray[i].boundingBox.width/HPIXELS_PER_CHAR - 2);
attr_off(color_set(color_pair,0),0);
color_pair++;
color++;
}
if(border_config->left.width > 0){
init_color(color, border_config->left.color.r, border_config->left.color.g, border_config->left.color.b);
init_pair(color_pair, color, COLOR_CYAN);//TODO get color at target location and init pair with that background
attr_on(color_set(color_pair,0),0);
mvvline(renderCommands.internalArray[i].boundingBox.y/VPIXELS_PER_CHAR + 1, renderCommands.internalArray[i].boundingBox.x/HPIXELS_PER_CHAR, '|', renderCommands.internalArray[i].boundingBox.height/VPIXELS_PER_CHAR - 1);
attr_off(color_set(color_pair,0),0);
color_pair++;
color++;
}
if(border_config->right.width > 0){
init_color(color, border_config->right.color.r, border_config->right.color.g, border_config->right.color.b);
init_pair(color_pair, color, COLOR_CYAN);//TODO get color at target location and init pair with that background
attr_on(color_set(color_pair,0),0);
mvvline(renderCommands.internalArray[i].boundingBox.y/VPIXELS_PER_CHAR + 1, renderCommands.internalArray[i].boundingBox.x/HPIXELS_PER_CHAR + renderCommands.internalArray[i].boundingBox.width/HPIXELS_PER_CHAR - 1, '|', renderCommands.internalArray[i].boundingBox.height/VPIXELS_PER_CHAR - 1);
attr_off(color_set(color_pair,0),0);
color_pair++;
color++;
}
break;
case CLAY_RENDER_COMMAND_TYPE_TEXT:
Clay_TextElementConfig *text_config = renderCommands.internalArray[i].config.textElementConfig;
attr_on(color_set(0,0),0);
int x = renderCommands.internalArray[i].boundingBox.x/HPIXELS_PER_CHAR;
int y = renderCommands.internalArray[i].boundingBox.y/VPIXELS_PER_CHAR; //text is referenced from bottom corner?
int w = renderCommands.internalArray[i].boundingBox.width/HPIXELS_PER_CHAR;
int h = renderCommands.internalArray[i].boundingBox.height/VPIXELS_PER_CHAR;
int line = 0;
int column = 0;
for (int k = 0; k < renderCommands.internalArray[i].text.length; k++) {
if (column >= w) {
column = 0;
line += 1;
}
mvaddch(y + line, x + column, renderCommands.internalArray[i].text.chars[k]);
column += 1;
}
break;
case CLAY_RENDER_COMMAND_TYPE_IMAGE:
case CLAY_RENDER_COMMAND_TYPE_SCISSOR_START:
case CLAY_RENDER_COMMAND_TYPE_SCISSOR_END:
case CLAY_RENDER_COMMAND_TYPE_CUSTOM:
default: continue;
}
}
attr_on(color_set(0,0),0);
mvwprintw(win, 0, 0, "Number of color pairs used: %i", color_pair);
refresh();//update the screen/window
}
//written by EmmanuelMess: https://github.com/nicbarker/clay/pull/91/commits/7ce74ba46c01f32e4517032e9da76bf54ecf7a43
static inline Clay_Dimensions ncurses_MeasureText(Clay_String *text, Clay_TextElementConfig *config) {
Clay_Dimensions textSize = { 0 };
float maxTextWidth = 0.0f;
float lineTextWidth = 0;
float textHeight = 1;
for (int i = 0; i < text->length; ++i)
{
if (text->chars[i] == '\n') {
maxTextWidth = maxTextWidth > lineTextWidth ? maxTextWidth : lineTextWidth;
lineTextWidth = 0;
textHeight++;
continue;
}
lineTextWidth++;
}
maxTextWidth = maxTextWidth > lineTextWidth ? maxTextWidth : lineTextWidth;
textSize.width = maxTextWidth*HPIXELS_PER_CHAR;
textSize.height = textHeight*VPIXELS_PER_CHAR;
return textSize;
}